#include<iostream> using namespace std; class student; class teacher { public : student *p; teacher(int x); int A; ~teacher(); }; teacher::teacher(int x) { A = x; p = new student(8); } teacher::~teacher() { delete p; } class student { friend class teacher; public: int a = 10; student(int x); }; student::student(int x) { a = x; } void func() { student s(100); cout << s.a << endl; teacher t(1); cout << t.A << endl; cout << t.p->a << endl; } int main() { func(); system("pause"); return 0; }这个代码问题出现在哪,该怎么解决
时间: 2024-03-12 12:48:56 浏览: 75
这段代码存在一个循环包含的问题,即 `class teacher` 中的 `student *p` 指针指向了 `class student`,而 `class student` 中又要使用 `class teacher`,这就导致了编译器无法处理两个类的定义顺序。要解决这个问题,可以将 `class student` 的定义放在 `class teacher` 的前面,或者使用前置声明来解决。修正后的代码如下:
```
#include<iostream>
using namespace std;
class student;
class teacher {
public:
student *p;
teacher(int x);
int A;
~teacher();
};
class student {
friend class teacher;
public:
int a = 10;
student(int x);
};
student::student(int x) {
a = x;
}
teacher::teacher(int x) {
A = x;
p = new student(8);
}
teacher::~teacher() {
delete p;
}
void func() {
student s(100);
cout << s.a << endl;
teacher t(1);
cout << t.A << endl;
cout << t.p->a << endl;
}
int main() {
func();
system("pause");
return 0;
}
```
阅读全文