#include<iostream> using namespace std; class student; class teacher { public: int a = 1; student p; teacher(int a); ~teacher(); }; teacher::teacher(int a) { cout << "teacher构造函数调用" << endl; this->a = a; // p = new student(100); } teacher::~teacher() { cout << "teacher析构函数调用" << endl; // delete p; } class student { public: //友元函数可以访问类中的公有和私有成员,不可以访问保护成员 friend void func2(student& s); friend class teacher; int a = 10; student(int x); ~student(); void func3(); private: int b = 20; }; student::student(int x) :a(x) { cout << "student 构造函数调用1" << endl; } student::~student() { cout << "student 析构函数调用!" << endl; } void student::func3() { cout << b << endl; } void func1() { student s1(100); cout << s1.a << endl; s1.func3(); func2(s1); cout << s1.a << endl; } //友元函数,全局函数做友元 //在形参中加入const防止传入的参数被改变,不加const则可以改变 void func2( student &s) { //传入普通类对象不可以改变类中的值,只能改变形参类的值 /*s.a = 123; cout<<s.a << endl; cout << s.b << endl;*/ ////传入指针可以改变类的值 /*s->a = 1000; s->b = 123; cout << s->a << endl; cout << s->b << endl;*/ ///传入引用也可以改变类中的值 //s.a = 12345; //s.b = 123456; cout << s.a << endl; cout << s.b << endl; } //类做友元 void func3() { student s1(10); cout << s1.a << endl; teacher t1(100); cout << t1.a << endl; //t1.p->a = 123456; cout << t1.p.a<< endl; } int main() { //成员函数做友元 //func1(); //类做友元 func3(); system("pause"); return 0; }你再看一遍我没有申明吗·1
时间: 2024-03-12 19:44:15 浏览: 47
非常抱歉,我之前的回答还是有误。在你提供的代码中,确实没有在`teacher`类之前声明`student`类的存在。
如果你想在`teacher`类中使用`student`类,你需要在`teacher`类的定义之前声明`student`类的存在,例如:
```cpp
// 声明 student 类的存在
class student;
// 定义 teacher 类
class teacher
{
public:
int a = 1;
student p;
teacher(int a);
~teacher();
};
class student
{
public:
int a = 10;
student(int x);
~student();
void func3();
};
teacher::teacher(int a)
{
cout << "teacher构造函数调用" << endl;
this->a = a;
}
teacher::~teacher()
{
cout << "teacher析构函数调用" << endl;
}
student::student(int x) :a(x)
{
cout << "student 构造函数调用1" << endl;
}
student::~student()
{
cout << "student 析构函数调用!" << endl;
}
void student::func3()
{
cout << b << endl;
}
void func1()
{
student s1(100);
cout << s1.a << endl;
s1.func3();
func2(s1);
cout << s1.a << endl;
}
void func2(student& s)
{
s.a = 12345;
s.b = 123456;
cout << s.a << endl;
cout << s.b << endl;
}
void func3()
{
student s1(10);
cout << s1.a << endl;
teacher t1(100);
cout << t1.a << endl;
//t1.p->a = 123456;
cout << t1.p.a << endl;
}
int main()
{
func3();
system("pause");
return 0;
}
```
在这个代码中,我们在`teacher`类之前声明了`student`类的存在,这样就可以在`teacher`类中使用`student`类了。需要注意的是,在使用`student`类之前,你还需要在代码中包含`student.h`头文件,或者将`student`类的定义放在当前文件中。
阅读全文