c++ - 如何定义非对称 + 运算符

标签 c++ operators operator-overloading redefine asymmetric

我正在尝试为 int + Date 定义 + 运算符并使其返回 一个 int .所以我定义了operator+作为成员来定义Date + int,我定义了一个非成员函数operator+(int, Date),但是在 main 中使用它时,它似乎没有使用该功能并产生错误。

class Date
{   
    int D, M, 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;
}

最佳答案

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

请考虑示例链接:

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

关于c++ - 如何定义非对称 + 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507715/

相关文章:

c++ - 读取二维数组作为 C++ 函数中的参数?

C++ While( cin >> x) 是如何工作的?

java - "|"中的 "int style = SWT.APPLICATION_MODAL | SWT.OK;"有什么作用(以及如何用谷歌搜索它)?

c# - C# : Is there something like the "IN" operator in SQL Server? 中的运算符

c++ - 了解运算符查找;哪个编译器是正确的?

c++运算符<<重载不打印出 vector

c++ - 如何将内存图像分配给 DLIB array2d 或图像?

C++ 期望主表达式在 "int"之前

c++ - istream 运算符重载 C++

c++ - 指针只是键值对吗?