我像这样在 C++ 上重载 + 运算符:
#include <iostream>
class Cent
{
private:
int m_nCent;
public:
Cent(){ };
Cent(int n);
int getCent() const;
void setCent(int);
friend Cent operator+(const Cent &c1, const Cent &c2);
friend Cent operator+(const Cent &c1, const int);
};
Cent::Cent(int n)
{
setCent(n);
}
int Cent::getCent() const
{
return Cent::m_nCent;
}
void Cent::setCent(int n)
{
Cent::m_nCent = n;
}
Cent operator+(const Cent &c1, const Cent &c2)
{
return Cent(c1.getCent() + c2.getCent());
}
Cent operator+(const Cent &c1, const int n)
{
return Cent(c1.getCent() + n);
}
int main()
{
Cent c1(5);
Cent c2(4);
Cent sum;
sum = c1 + c2;
std::cout << sum.getCent() << std::endl;
sum = c1 + 7;
std::cout << sum.getCent() << std::endl;
sum = 9 + c1;
std::cout << sum.getCent() << std::endl;
return 0;
}
基于这段代码,我必须用两个函数重载 + 运算符,一个用于 (Cent,int) 的函数和另一个用于 (int,Cent) 的函数,我只实现了 (Cent,int) 的情况,但在 main 上我使用 + 运算符for (int,Cent) 确实有效!我怎么了?
我在 Linux 3.13 上使用 GCC v4.8.2。
最佳答案
你有一个隐式转换构造函数 Cent(int)
。 9 + c1
调用将扩展为 Cent(9) + c1
并调用 Cent, Cent
重载。
关于c++ - 不需要两个函数 for + 重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043984/