我已经编写了以下代码,以帮助我查看继承以及调度/双调度如何在C ++中运行,但它不会编译。我已经找到了班级原型/前瞻性声明,但我已经做到了,但我仍然收到错误" B是一个不完整的类型"," SubB是一个不完整的类型"等等问题是什么?
#include <iostream>
class B;
class SubB;
class A {
public:
void talkTo(B b){
std::cout << "A talking to instance of B" << std::endl;
}
void talkTo(SubB sb){
std::cout << "A talking to instance of SubB" << std::endl;
}
};
class SubA : A {
public:
void talkTo(B b){
std::cout << "SubA talking to instance of B" << std::endl;
}
void talkTo(SubB sb){
std::cout << "SubA talking to instance of SubB" << std::endl;
}
};
class B {
public:
void talkTo(A a){
std::cout << "B talking to instance of A" << std::endl;
}
void talkTo(SubA sa){
std::cout << "B talking to instance of SubA" << std::endl;
}
};
class SubB : B {
public:
void talkTo(A a){
std::cout << "SubB talking to instance of A" << std::endl;
}
void talkTo(SubA sa){
std::cout << "SubB talking to instance of SubA" << std::endl;
}
};
将参数更改为引用使得这项工作(来自R Sahu的帮助)但为什么现在没有这项工作?
class A {
public:
void talkTo(B &b){
//std::cout << "A talking to instance of B" << std::endl;
b.talkTo(this);
}
void talkTo(SubB &sb){
//std::cout << "A talking to instance of SubB" << std::endl;
sb.talkTo(this);
}
};
class B {
public:
void talkTo(A &a){
std::cout << "B talking to instance of A" << std::endl;
}
void talkTo(SubA &sa){
std::cout << "B talking to instance of SubA" << std::endl;
}
};
class SubB : B {
public:
void talkTo(A &a){
std::cout << "SubB talking to instance of A" << std::endl;
}
void talkTo(SubA &sa){
std::cout << "SubB talking to instance of SubA" << std::endl;
}
};
A a;
SubA subA;
B b;
SubB subB;
a.talkTo(b);
a.talkTo(subB);
答案 0 :(得分:0)
当你有一个前向声明时,你可以使用只有类型的引用:指针和引用是最明显的引用。
而不是
void talkTo(B b){
std::cout << "A talking to instance of B" << std::endl;
}
void talkTo(SubB sb){
std::cout << "A talking to instance of SubB" << std::endl;
}
使用
void talkTo(B const& b){
std::cout << "A talking to instance of B" << std::endl;
}
void talkTo(SubB const& sb){
std::cout << "A talking to instance of SubB" << std::endl;
}