根据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;
}发布于 2010-08-16 21:37:12
对于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++的经验中从未见过这样的事情。
如果您想要将从整型转换为包装型,反之亦然,那么您必须提供以下内容:
1)从int到wrapint -一个适当的构造函数,允许从int进行隐式转换;作为旁注,注意当使用这种隐式转换时,您应该真正确保行为是预期的,并且在问题范围内(查看C++的explicit关键字以获得进一步的“启蒙”)
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;
}发布于 2010-08-16 21:30:16
operator=应该修改左边的值,左边的值必须是类类型。返回值(通常为*this)通常被忽略,除非您链接赋值/其他函数调用(例如,将b = c的结果赋给a的a = b = c; )。
如果您希望能够将wrapint分配给内置的int,则可以通过为wrapint定义强制转换操作符来实现
wrapint::operator int() const { return m_iCurrentNumber; }现在,当您尝试将1赋给一个整数时,wrapint将被隐式转换为一个整数。
int a;
wrapint w;
a = w; //== a = w.operator int() https://stackoverflow.com/questions/3492979
复制相似问题