帮忙找下错误,刚学C++,麻烦了
#include <iostream>
using namespace std;
class Teacher;
class Student
{
public:
Student(int id,char *name)
{
this-> id=id;
strcpy(this-> name,name);
}
friend void Teacher::display(Student& s);
private:
int id;
char name[20];
};
class Teacher
{
public:
Teacher(int tid,char *name)
{
this-> tid=tid;
strcpy(this-> tname,name);
}
void display(Student& s);
private:
int tid;
char tname[20];
}
void Teacher::display(Student& s)
{
cout < <s.id < < " " < <s.name < <endl;
};
int main()
{
Student s1(12, "Chris ");
s1.display(s1);
cin.get();
}
编译的时候,有很多错误,是关于友元的问题,谢谢了
[解决办法]
三个错误:
1、Teacher类定义后面掉了; ..。语法错误。。。。
2、声明为友元,那么,被声明的应该先被定义,注意是定义,而你class Teacher只是个声明
不行,所以要把这两个类的定义次序掉过来。
3、友元只是一个访问授权。也就说只是权限。并不代表他拥有这个成员(函数)。
所以 s1.display(s1); 这里是没有这个成员的。
改正如下:
class Student;
class Teacher
{
public:
Teacher(int tid,char *name)
{
this-> tid=tid;
strcpy(this-> tname,name);
}
void display(Student& s);
private:
int tid;
char tname[20];
};
class Student
{
public:
Student(int id,char *name)
{
this-> id=id;
strcpy(this-> name,name);
}
friend void Teacher::display(Student& s);
private:
int id;
char name[20];
};
void Teacher::display(Student& s)
{
cout < <s.id < < " " < <s.name < <endl;
};
int main()
{
Student s1(12, "Chris ");
//s1.display(s1);
Teacher t1(15, "Tech1 ");
t1.display(s1);
cin.get();
}