【问题标题】:How to define asymmetric + operator如何定义非对称 + 运算符
【发布时间】:2012-02-29 22:32:56
【问题描述】:

为什么这不起作用?我正在尝试为 int+Date 定义 + 运算符并使其返回一个 int。所以我将operator+定义为一个成员来定义Date+int,并且我定义了一个非成员函数operator+(int, Date),但是在main中使用它的时候似乎并没有使用那个函数并产生错误

class Date
{   int D;
    int M;
    int Y;
public:
    Date();
    Date(int, int, int);
    ~Date(void);
    int getDay() const;
    Date operator+(Date) const;
    Date operator+(int) const;
};

Date::Date()
{
    D = 15;
    Y = 2012;
    M = 2;
}
Date::Date(int d, int m, int y)
{
    D = d;
    Y = y;
    M = m;
}
Date::~Date(void)
{
}    
int Date::getDay() const
{
    return D;
}
Date Date::operator+(Date d) const
{
    return Date(d.D+D,d.M+M,d.Y+Y);
}
Date Date::operator+(int d) const
{
    return Date(d+D,M,Y);
}

int operator+(int i,Date d) // This is what is wrong apparently.
{
    return i + d.getDay();
}

int main ()
{
Date d = Date();
int i = 7 + d; // This is what generates the error at compile time.
cout << i;
return 0;
}

【问题讨论】:

  • 它编译并运行正常:ideone.com/8Jbt8.
  • 好吧,我显然很愚蠢,我的错。在我的代码中,Date 类在一个单独的文件中,我忘记在头文件中包含 operator+ 函数......这里没有问题,因为它是在相同的代码中定义的......感谢大家的反应!

标签: c++ operators operator-overloading redefine asymmetric


【解决方案1】:

您可以将其定义为类外的友好函数。

请考虑示例链接:

http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2017-08-03
    • 2012-01-05
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多