簡體   English   中英

如何定義非對稱+運算符

[英]How to define asymmetric + operator

為什么這不起作用? 我正在嘗試為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;
}

您可以將其定義為課堂外的友好功能。

請通過示例考慮該鏈接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM