簡體   English   中英

重載重載運算符=?

[英]Overloading overloaded operator=?

當我需要完成不同的工作時(取決於rval和lval類型),該怎么辦? 定義多個過載時彈出錯誤“ operator = isambiguous”。

非常感謝任何想法或技巧(指向教程的鏈接),因為我今天才發現有關運算符重載的知識。

提前致謝!

編輯:

是的,我會使用C ++ 0x,因為我可以使用它,只是我看不到它會對代碼有什么影響?

這是我使用atm的兩種情況,如果我理解得很好,則lval是不同的,因此可以識別它們。 目的是轉換為適當的類型。

int wrapint::operator=(int)
{
    return m_iCurrentNumber;
}

void wrapint::operator=(const int& rhs)
{
    m_iCurrentNumber = rhs;
}

對於wrapint = wrapint情況:

wrapint& wrapint::operator=(const wrapint& rhs)
{
    // test for equality of objects by equality of address in memory
    // other options should be considered depending on specific requirements
    if (this == &rhs) return *this;

    m_iCurrentNumber = rhs.m_iCurrentNumber;

    return *this;
}

我必須說以上內容是賦值運算符的正確簽名。 我認為您提供的簽名是錯誤的,或者至少我在C ++的經驗中從未見過這樣的事情。

如果你想從一個int 轉換為wrapint和周圍,你必須提供以下的其他方式,則:

1)從int到wrapint-允許從int隱式轉換的適當構造函數; 附帶說明 ,在使用此類隱式轉換時,您應該真正確保行為是有意的並且在問題范圍之內(請參閱C ++的顯式關鍵字以獲取進一步的“啟發”)

2)從wrapint到int-正確的演員

下面是一個示例:

#include <iostream>

class wrapint
{ 
public:
   wrapint() : m_iCurrentNumber(0)
   { 

   }

   // allow implicit conversion from int
   // beware of this kind of conversions in most situations
   wrapint(int theInt) : m_iCurrentNumber(theInt)
   { 

   }

   wrapint(const wrapint& rhs) 
   {
    if (this != &rhs) 
        this->m_iCurrentNumber = rhs.m_iCurrentNumber; 
   }

   wrapint& operator=(const wrapint& rhs);

   operator int ()
   {
        return m_iCurrentNumber;
   }

 private:
     int m_iCurrentNumber;
 };

 wrapint& wrapint::operator=(const wrapint& rhs)
 {
     // test for equality of objects by equality of address in memory
     // other options should be considered depending on specific requirements
     if (this == &rhs) return *this;

     m_iCurrentNumber = rhs.m_iCurrentNumber;
     return *this;
 }

 using namespace std;

 int main()
 {
     // this will be initialized to 0
     wrapint theOne;
     // this will be 15
     wrapint theOtherOne = 15;

     cout << "The one: " << theOne << "\n";
     cout << "The other one: " << theOtherOne << "\n";

     theOne = theOtherOne;

     int foobar = theOne;
     // all should be 15
     cout << "The one: " << theOne << "\n";
     cout << "The other one: " << theOtherOne << "\n";
     cout << "The foobar: " << foobar << "\n";
     return 0;
 }

應該用operator=修改左側的值,並且左側的值必須是類類型。 的返回值(通常*this )主要被忽略,當要鏈接分配/其他函數調用(例如,除了a = b = c;其中的結果b = c被分配給a )。

如果您希望能夠將wrapint分配給內置int ,則可以通過為wrapint定義一個wrapint運算符來wrapint

wrapint::operator int() const { return m_iCurrentNumber; }

現在,當您嘗試將一個分配給int時, wrapint將隱式轉換為int。

int a;
wrapint w;
a = w;  //== a = w.operator int() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM