gpt4 book ai didi

c++ - 重载重载运算符=?

转载 作者:行者123 更新时间:2023-11-30 03:10:07 25 4
gpt4 key购买 nike

当我需要根据 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;
}

最佳答案

对于 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++ 的 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;
}

关于c++ - 重载重载运算符=?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3492979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com