Azh*_*bal 13 c++ operator-overloading operators operator-keyword
我有以下课程: -
class myclass
{
size_t st;
myclass(size_t pst)
{
st=pst;
}
operator int()
{
return (int)st;
}
int operator+(int intojb)
{
return int(st) + intobj;
}
};
Run Code Online (Sandbox Code Playgroud)
只要我像这样使用它,这个工作正常: -
char* src="This is test string";
int i= myclass(strlen(src)) + 100;
Run Code Online (Sandbox Code Playgroud)
但我无法做到这一点: -
int i= 100+ myclass(strlen(src));
Run Code Online (Sandbox Code Playgroud)
任何想法,我怎么能实现这个?
Bri*_*ndy 23
在类之外实现运算符重载:
class Num
{
public:
Num(int i)
{
this->i = i;
}
int i;
};
int operator+(int i, const Num& n)
{
return i + n.i;
}
Run Code Online (Sandbox Code Playgroud)
Jef*_*f L 12
您必须将运算符实现为非成员函数,以允许左侧的原始int.
int operator+( int lhs, const myclass& rhs ) {
return lhs + (int)rhs;
}
Run Code Online (Sandbox Code Playgroud)
这里的其他答案将解决该问题,但以下是我在执行此操作时使用的模式:
class Num
{
public:
Num(int i) // Not explicit, allows implicit conversion to Num
: i_ (i)
{
}
Num (Num const & rhs)
: i_ (rhs.i_)
{
}
Num & operator+= (Num const & rhs) // Implement +=
{
i_ += rhs.i_;
return *this;
}
private:
int i_;
};
//
// Because of Num(int), any number on the LHS or RHS will implicitly
// convert to Num - so no need to have lots of overloads
Num operator+(Num const & lhs, Num const & rhs)
{
//
// Implement '+' using '+='
Num tmp (lhs);
tmp+=rhs;
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
这种方法的主要优点之一是您的函数可以相互实现,从而减少所需的总体代码量。
更新:
为了避免性能问题,我可能会将非成员运算符+定义为内联函数,如下所示:
inline Num operator+(Num lhs, Num const & rhs)
{
lhs+=rhs;
return lhs;
}
Run Code Online (Sandbox Code Playgroud)
成员操作也是内联的(因为它们是在类主体中声明的),因此所有代码应该非常接近添加两个原始int对象的成本。
最后,正如 jalf 所指出的,一般需要考虑允许隐式转换的后果。上面的示例假设从整型类型转换为“Num”是明智的。