【问题标题】:Confused why it got solved by using friend function困惑为什么它通过使用朋友功能得到解决
【发布时间】:2021-07-29 02:34:54
【问题描述】:

我在作业中有这个问题。

问题: 为 Date 类实现 + 和 - 运算符,您可以在其中使用构造函数给出日期,并给出额外的 n 值。现在我们必须使用 operator + 和 operator - 将之前拍摄的日期更改为 n 值。

我已经这样做了,但它给出了一个错误:operator+(Date&, int) 必须采用零或一个参数

class Date
{
      int day;
      int month;
      int year;
      public:
             Date(int d,int m,int y)
             {
                   day=d;
                   month=m;
                   year=y;
             }

             Date operator-(Date &x,int y)
            {
                return Date(x.day-y, x.month, x.year);
            }
            
            Date operator+(Date &x,int y)
            {
                return Date(x.day+y, x.month, x.year);
            }
             void display()
             {
                  cout<<"Date:"<<day<<"-"<<month<<"-"<<year<<endl;
             }
};

我在网上搜索后发现:

class Date{
    private:
        int day;
        int mth;
        int year;
        
    public:
        Date(int a,int b,int c){
            day = a;
            mth = b;
            year = c;
        }
        
        friend Date operator +(Date &,int);
        friend Date operator -(Date &,int);
        
        void print(void){
            cout <<"Date: " << day << " - " << mth << " - " << year << endl;
        }
};

Date operator +(Date& a,int n){
    Date d(a.day+n,a.mth,a.year);
    return(d);
}
        
Date operator -(Date& a,int n){
    Date d(a.day-n,a.mth,a.year);
    return(d);
}

我的疑问:两者都是一样的,但是他使用了朋友功能并且它得到了解决。在这两种情况下,运算符重载函数都是相同的,并且错误也指向该函数。这个友元函数如何解决我的运算符重载函数中的问题或任何错误?

【问题讨论】:

    标签: c++11 operator-overloading friend-function


    【解决方案1】:
    1. 在第一个代码 sn-p 中,运算符函数是成员函数,因此它们应该是 operator+(int) 而不是 operator+(Date&amp;, int),因为 Date &amp; 类型的第一个参数是隐式的。

    2. 在第二个代码 sn-p 中,运算符函数不是成员函数,因此您需要一个 friend 限定符来访问 Date 的私有成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多