如何解决C++中的菱形问题?
How to solve diamond issue in C++?
我有以下测试程序
#include<iostream>
using namespace std;
class Faculty {
// data members of Faculty
public:
Faculty(int x) {
cout<<"Faculty::Faculty(int ) called"<< endl;
}
void test() {
cout<<"Faculty::test called" << endl;
}
};
class Student {
// data members of Student
public:
Student(int x) {
cout<<"Student::Student(int ) called"<< endl;
}
void test() {
cout<<"Student::test called" << endl;
}
};
class TA : virtual public Faculty, virtual public Student {
public:
TA(int x):Student(x), Faculty(x) {
cout<<"TA::TA(int ) called"<< endl;
}
};
int main() {
TA ta1(30);
ta1.test();
}
编译过程中出现错误
8be257447d8c26ef785b1a60f2884a.cpp: In function 'int main()':
748be257447d8c26ef785b1a60f2884a.cpp:36:6: error: request for member 'test' is ambiguous
ta1.test();
^
748be257447d8c26ef785b1a60f2884a.cpp:22:7: note: candidates are: void Student::test()
void test() {
^
748be257447d8c26ef785b1a60f2884a.cpp:11:7: note: void Faculty::test()
void test() {
^
即使我在这里使用虚拟继承。有什么解决办法吗?
此处不需要 virtual
关键字,classes Student
和 Faculty
与公共 class 的继承无关。
如果你想在 TA
中使用特定的方法,你可以将 using Student::test;
或 using Faculty::test;
放在 TA
class 声明中。
我希望这个例子纯粹出于教育目的,因为如果它 used/planned 用于实际应用 - 这表明设计出了问题:)
您的 TA
class 中只有两个 test()
方法,一个继承自 Faculty
,另一个继承自 Student
,编译器正确通知您它无法决定您要呼叫哪一个。
您需要通过明确说明要调用哪个方法来解决此问题:
TA ta1(30);
ta1.Faculty::test();
或者应该如何处理对象(这将暗示调用哪个方法):
((Faculty &)ta1).test();
我有以下测试程序
#include<iostream>
using namespace std;
class Faculty {
// data members of Faculty
public:
Faculty(int x) {
cout<<"Faculty::Faculty(int ) called"<< endl;
}
void test() {
cout<<"Faculty::test called" << endl;
}
};
class Student {
// data members of Student
public:
Student(int x) {
cout<<"Student::Student(int ) called"<< endl;
}
void test() {
cout<<"Student::test called" << endl;
}
};
class TA : virtual public Faculty, virtual public Student {
public:
TA(int x):Student(x), Faculty(x) {
cout<<"TA::TA(int ) called"<< endl;
}
};
int main() {
TA ta1(30);
ta1.test();
}
编译过程中出现错误
8be257447d8c26ef785b1a60f2884a.cpp: In function 'int main()':
748be257447d8c26ef785b1a60f2884a.cpp:36:6: error: request for member 'test' is ambiguous
ta1.test();
^
748be257447d8c26ef785b1a60f2884a.cpp:22:7: note: candidates are: void Student::test()
void test() {
^
748be257447d8c26ef785b1a60f2884a.cpp:11:7: note: void Faculty::test()
void test() {
^
即使我在这里使用虚拟继承。有什么解决办法吗?
此处不需要 virtual
关键字,classes Student
和 Faculty
与公共 class 的继承无关。
如果你想在 TA
中使用特定的方法,你可以将 using Student::test;
或 using Faculty::test;
放在 TA
class 声明中。
我希望这个例子纯粹出于教育目的,因为如果它 used/planned 用于实际应用 - 这表明设计出了问题:)
您的 TA
class 中只有两个 test()
方法,一个继承自 Faculty
,另一个继承自 Student
,编译器正确通知您它无法决定您要呼叫哪一个。
您需要通过明确说明要调用哪个方法来解决此问题:
TA ta1(30);
ta1.Faculty::test();
或者应该如何处理对象(这将暗示调用哪个方法):
((Faculty &)ta1).test();