c++ - 不需要两个函数 for + 重载?

标签 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;
}

基于这段代码,我必须用两个函数重载 + 运算符,一个用于 (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/

相关文章:

c++ - 关于 C++ 中模板上重载运算符的一些编译器错误

c++ - 什么是 friend ostream

c++ - 十六进制浮点字面量

c++ - 使用 Qdom 忽略无效的 XML 标签?

c++ - operator= 重载分数数学的双指针

模板类上的 C++ 运算符重载

c++ - 设计一个可以在 if 语句中测试的类?

c++ - Visual Studio C++ 项目中所需的 DLL

c++ - 如何声明和初始化类中的静态成员?

python - Python 的内置打印为什么/如何允许 ">>"运算符?