重载重载运算符=?

时间:2010-08-16 12:14:43

标签: c++ operator-overloading

根据rval和lval类型,当我需要完成不同的工作时,我该怎么办? 弹出定义的几个重载,错误'operator = is ambiguous'。

非常感谢任何想法或提示(指向教程的链接),因为我今天才发现有关运算符重载的信息。

提前致谢!

编辑:

是的,我使用C ++ 0x,因为我可以使用它,只是我看不出它会对代码产生什么影响?

这两种情况我使用atm,如果我得到它lval是不同的,所以它们是可识别的。目的是转换为适当的类型。

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

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

2 个答案:

答案 0 :(得分:2)

对于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转换为包装,反之则必须提供以下内容:

1)从int到wrapint - 一个允许从int进行隐式转换的正确构造函数;作为一个 note ,你应该确实在使用这种隐式转换时确保行为是有意的并且在问题范围内(看看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;
 }

答案 1 :(得分:1)

operator=应该修改左手值,而左手值必须属于类类型。除非链接赋值/其他函数调用(例如*this,其中a = b = c;的结果已分配给b = c),否则返回值(通常为a)将被忽略。

如果您希望能够将wrapint分配给内置int,则可以通过为wrapint

定义强制转换运算符来实现
wrapint::operator int() const { return m_iCurrentNumber; }

当你尝试将一个赋值给int时,wrapint将被隐式转换为int。

int a;
wrapint w;
a = w;  //== a = w.operator int() 
相关问题