读书人

C++ 友元成员函数,该怎么解决

发布时间: 2012-04-09 13:41:25 作者: rapoo

C++ 友元成员函数
在将尝试学习C++友元成员函数时,出错。始终调试不出来,还请帮忙看看。谢谢先~~~

源码如下:
Student.h

C/C++ code
#ifndef STUDENT_H_#define STUDENT_H_#include <string>#include <iostream>using namespace std;class Student {    //friend class Teacher;// 此处若使用友元类,程序编译通过    friend void Teacher::print_student_info();public:    Student();    virtual ~Student();private:    string username;    void self_info();};#endif /* STUDENT_H_ */


Student.cpp
C/C++ code
#include "Student.h"Student::Student() :    username("Student_A") {    // TODO Auto-generated constructor stub}Student::~Student() {    // TODO Auto-generated destructor stub}void Student::self_info() {    cout << "My Username is " << username << endl;}


Teacher.h
C/C++ code
#ifndef TEACHER_H_#define TEACHER_H_#include "Student.h"class Teacher {public:    Teacher();    virtual ~Teacher();    void print_student_info();private:    Student student;};#endif /* TEACHER_H_ */

Teacher.cpp
C/C++ code
#include "Teacher.h"Teacher::Teacher() :    student(Student()) {    // TODO Auto-generated constructor stub}Teacher::~Teacher() {    // TODO Auto-generated destructor stub}void Teacher::print_student_info() {    cout << "The only student name = " << student.username << endl;}


最后主程序:
C/C++ code
#include <iostream>using namespace std;#include "Teacher.h"int main() {    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!    Teacher t;    t.print_student_info();    return 0;}


如上代码,也就是想将Teacher类中的函数print_student_info声明为Student的友元函数,但是始终无法编译通过,在下新手,烦请各位帮忙看看,在我的调试中,如果将Teacher声明为Student的友元类的话,则编译通过。我想尝试使用友元成员函数,但是不行。

之前也有尝试将Teacher和Student写在一个文件中,可以编译通过,但是想必最后的程序开发之类的东西还是需要将两个类分别放在不同的文件中。

还请各位大侠不吝赐教!谢谢先。

[解决办法]
Student.h引入Teacher.h??
[解决办法]
Student.h


#ifndef STUDENT_H_
#define STUDENT_H_
#include <string>
#include <iostream>
using namespace std;
?class Teacher; //这里声明一下
class Student {
? //friend class Teacher;// 此处若使用友元类,程序编译通过
? friend void Teacher::print_student_info();
public:
? Student();
? virtual ~Student();
private:
? string username;
? void self_info();
};

#endif /* STUDENT_H_ */

[解决办法]
申明一个类的成员函数为本类的友元前
这个类必须先有定义

或者这样说:必须先定义包含成员函数的类
才能将成员函数设为友元
[解决办法]
参考:
友元函数和友元类
[解决办法]
还有一点需要提醒楼主,友元函数不是成员函数。
[解决办法]
必须先定义包含成员函数的类,才能将成员函数设为友元,而不必预先声明类和非成员函数来将他们设为友元。
? Student.h没有包含teacher.h的声明和teacher.cpp的实现文件,你将这两个文件包含进去看看!!

读书人网 >C++

热点推荐