Create a constructor with an argument of type int
.
jakeint(int x)
{
_setFromInt(x);
}
With that, you could use:
jakeint ji = 8;
as well as
jakeint ji(8);
質問
I have an object and I have overloaded the = operator to accept an int.
class jakeint
{
private:
vector<short> theInt;
void _setFromInt(int x);
//operators
public:
jakeint& jakeint::operator=(int x)
{
_setFromInt(x);
return *this;
}
};
This works perfectly fine. The problem is that if I want to use the = operator, I have to do this:
jakeint ji;
ji = 8;
I do want this to be doable, but I also would like to be able to do this:
jakeint ji = 8;
How would I go about doing this?
I realize I could just add it to the constructor and do
jakeint ji(8);
but I want these to work just like integers do.
解決
Create a constructor with an argument of type int
.
jakeint(int x)
{
_setFromInt(x);
}
With that, you could use:
jakeint ji = 8;
as well as
jakeint ji(8);
他のヒント
Just add it to the constructor. You can specify the initialization with =
or not, it doesn't matter. It invokes the constructor either way.
You can make a constructor with argument for jakeint ji = 8;
and jakeint ji(8);
, such as:
jakeint(int x) {
_setFromInt(x);
}
And if you define a constructor by yourself, you need to define a default constructor too if you still want to use jakeint ji;
, such as:
jakeint() {
_setFromInt(0);
}
You need a constructor that takes an int, and also a copy constructor. The implicit copy constructor is fine in this case. (The actual call to the copy ctor is usually elided.)
jakeint ji = 8;
is just a shorthand alias for jakeint ji(8);
, they are identical, so you do need to add a constructor that takes an int
as input, as other people have showed you.