如何定义非对称+运算符

时间:2012-02-29 22:32:56

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

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

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

1 个答案:

答案 0 :(得分:2)

您可以将其定义为课堂外的友好功能。

请考虑一个示例链接:

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