繁体   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