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
关键字,类Student
和Faculty
不是通过从公共类继承来关联的。
如果要在TA
中使用特定方法,可以将using Student::test;
或using Faculty::test;
放在类声明TA
。
我希望这个例子纯粹是出于教育目的,因为如果它被使用/计划用于实际应用 - 这表明设计:)出了问题
TA
类中只有两个test()
方法,一个继承自Faculty
,另一个继承自Student
,编译器正确地通知您它无法决定要调用哪个方法。
您需要通过明确说明要调用的方法来解决此问题:
TA ta1(30);
ta1.Faculty::test();
或者应该如何处理对象(这将意味着调用哪个方法(:
((Faculty &)ta1).test();
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么是钻石问题?是一系列问题还是特定问题?
- 在钻石问题的求解中,为什么要虚拟地继承两次grand-parent类
- C++如何解决钻石问题?
- C++解决没有虚拟继承的钻石继承问题
- 多种继承C 的钻石问题
- 如何解决钻石问题的这种歧义
- 解决QT类的特定C 钻石问题
- 复杂的钻石问题:C++虚拟继承
- 为什么使用声明不能解决钻石问题?
- 当 C++ 遇到钻石问题时会发生什么
- 尝试使用虚拟继承解决钻石问题
- C++:钻石问题
- 无法消除c++中的钻石问题
- C++解决钻石问题