為什么將2個類放在同一個.cpp文件會出現錯誤呢
#include<iostream>
#include<string>
using namespace std;
class time
{
friend void printTime(time &t);//將printTime聲明為time的友元函數
public:
time(int hour, int min, int sec)
{
this->hour = hour;
this->min = min;
this->sec = sec;
cout << "class time start" << endl;
}
private:
int hour, min, sec;
};
class match
{
public:
friend void printTime(time &t)
{
cout << t.hour << ":" << t.min << ":" << t.sec << endl;
}
};
int main()
{
time t(12, 0, 0);
match m;
m.printTime(t);
return 0;
}
2019-03-21
你這代碼問題很多,首先聲明友元函數時,需要指出哪個類的成員函數作友元,即 friend Match::printTime(Time &t);之后F5會出現編譯錯誤,原因在于Match未聲明,即在class Time{}前聲明class Match; 之后F5編譯出現錯誤,原因是雖然聲明了Match但編譯器不知道printTime是Match的成員函數,因此應該先編寫類Match,再編寫類Time,其中由于編寫類Match時有void printTime(Time &t),所以需要先聲明Time即classTime,此外一定要注意先聲明,后使用
正確代碼:
#include<iostream>
using namespace std;
class Time;
class Match
{
public:
void printtime(Time &t);
};
class Time?
{
friend void Match::printtime(Time &t);
public:
Time(int hour, int min, int sec);
private:
int m_ihour;
int m_imin;
int m_isec;
};
void Match::printtime(Time &t)
{
cout << t.m_ihour << ":" << t.m_imin << ":" << t.m_isec << endl;
}
Time::Time(int hour, int min, int sec)
{
m_ihour = hour;
m_imin = min;
m_isec = sec;
}
int main(void)
{
Time time(19, 58, 10);
Match c;
c.printtime(time);
system("pause");
return 0;
}
2018-02-27
class match? 類中?friend void printTime(time &t), 多了個?friend? 關鍵字