繁体   English   中英

重载运算符以与C ++中的另一个类一起使用

[英]Overloading operator to use with another class in C++

有什么方法可以重载> (大于)运算符,从而能够执行以下操作:

myClass *a = new myClass(1);
myClass *b = new myClass(3);

if(a > b) //it should compare the int values from the constructors
  //do something

我尝试重载运算符,但遇到各种错误。 我正在使用VC ++。

您不能重载指针的运算符,因为它们是原始类型(并且您不能在两个参数都是原始类型的情况下创建重载)。 相反,您可以为用户定义类型的对象(而不是指向它们的指针)重载运算符:

class myClass
{
    // ...
public:
    bool operator>(const myClass & right) const
    {
        return this->whatever()>right.whatever();
    }
};

myClass *a = new myClass(1);
myClass *b = new myClass(3);

if(*a > *b) //it should compare the int values from the constructors
  //do something

请注意,如果您没有特殊的理由在堆上分配内容,最好将其分配在堆栈上:

myClass a(1);
myClass b(3);
if(a > b)
    // do something

尝试

class MyClass
{
    int value;
    public:
        bool operator>(MyClass const& rhs) const
        {
             return value > rhs.value;
        }

        MyClass(int v):value(v){}

};

int main()
{
     MyClass a(1);
     MyClass b(3);

     if (a > b) { PLOP } else { POOP }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM