簡體   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