C++如何解决钻石问题?

How to solve diamond issue in C++?

本文关键字:钻石 问题 解决 何解决 C++      更新时间:2023-10-16

>我有以下测试程序

#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关键字,类StudentFaculty不是通过从公共类继承来关联的。

如果要在TA中使用特定方法,可以将using Student::test;using Faculty::test;放在类声明TA

我希望这个例子纯粹是出于教育目的,因为如果它被使用/计划用于实际应用 - 这表明设计:)出了问题

TA类中只有两个test()方法,一个继承自Faculty,另一个继承自Student,编译器正确地通知您它无法决定要调用哪个方法。

您需要通过明确说明要调用的方法来解决此问题:

TA ta1(30);
ta1.Faculty::test();

或者应该如何处理对象(这将意味着调用哪个方法(:

((Faculty &)ta1).test();