mey*_*sam 1 c++ operator-overloading
我在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;
}
Run Code Online (Sandbox Code Playgroud)
基于这个代码,我必须使用两个函数重载+运算符,一个函数用于(Cent,int),另一个函数用于(int,int),我只实现(Cent,int)情况但在main上我使用+运算符为(int ,分),这是真正的工作!我怎么了?
我在Linux 3.13上使用GCC v4.8.2.
你有一个隐式的转换构造函数Cent(int).的9 + c1通话将扩大到Cent(9) + c1并调用Cent, Cent过载.