c++中友元函数显示错误

Friend function in c++ showing error

本文关键字:显示 错误 函数 友元 c++      更新时间:2023-10-16
    #include <iostream>
    using namespace std;
    class time{
        int date,month,year;
    public:
       void gettime(){
            cout<<"enter the (date/month/year)n";
            cin>>date>>month>>year;
        }
        void show(){
            cout<<"Your age is:-"<<date<<month<<year;
        }
        friend time Add(time a1,time a2);
    };
    time Add(time a1,time a2){
            time temp;
            if(a2.date<a1.date)
            {
                a2.date=a2.date+30;
                temp.date=a2.date-a1.date;
                a2.month=a2.month-1;
            }
            else
                temp.date=a2.date-a1.date;
            if(a2.month<a1.month)
            {
                a2.month=a2.month+12;
                temp.month=a2.month-a1.month;
                a2.year=a2.year-1;
            }
            else
                temp.month=a2.month-a1.month;
            temp.year=a2.year-a1.year;
            return (temp);
    }
    int main()
    {
        time a1,a2,t3;
        a1.gettime();
        a2.gettime();
        t3=Add(a1,a2); //this is the friend function
        t3.show();
        return 0;
    }

这可以在Dev c++中工作,但不能在gcc和任何其他编译器中工作。

age.cpp:17:1: error: ‘time’ does not name a type
 time Add(time a1,time a2){
 ^
age.cpp: In function ‘int main()’:
age.cpp:42:7: error: expected ‘;’ before ‘a1’
  time a1,a2,t3;
       ^
age.cpp:43:2: error: ‘a1’ was not declared in this scope
  a1.gettime();
  ^
age.cpp:44:2: error: ‘a2’ was not declared in this scope
  a2.gettime();
  ^
age.cpp:45:2: error: ‘t3’ was not declared in this scope
  t3=Add(a1,a2);
  ^
age.cpp:45:14: error: ‘Add’ was not declared in this scope
  t3=Add(a1,a2);
              ^

iostream正在拉入time.hctime。这是在全局命名空间和/或std命名空间中声明函数time_t time(time_t *t);,导致名称冲突。

要解决这个问题,请重命名您的类,或者在您自己的命名空间中定义它。

我还建议远离using namespace std;,以避免其他名称冲突或歧义,尽管它不是您在这种情况下问题的原因。