我正在构建一个接口,使用单独的变量来访问各个接口会有点不方便,如果我能以某种方式创建两者的并集,那将会很棒。
在档案中:
struct A{
virtual int auu() { return 41; }
};
struct B{
virtual int boo() { return 43; }
};
在另一个档案中:
#include <path to A, B>
struct C : public A, public B{
int auu() { return 20; }
int boo() { return 22; }
};
另一个文件:
#include <declaration of A and B, but not C>
void doSth(A* a)
{
B * b = dynamic_cast<B*>(a);
/* I can only call auu with a */
a->auu();
/* I can only call boo with b */
b->boo;
/* Something like this would be ideal: */
<??? type> * C_interface = dynamic_interface_cast<B*>(a)
C_interface->auu();
C_interface->boo();
}
那么只通过一个指针变量调用auu和boo并且不知道C&C的实现(不将其转换为)?另外,我还想避免创建与C类无关的继承层次结构。
可能答案是否定的,但是我很好奇这样的想法是否来自语言开发人员,因为我的原始思想并不是一个如此遥远的想法。
编辑: 实际上,A和B是抽象的。 A是一个Simulation对象,它具有size()和length()等方法。 B是一个IO接口,实现了getter和setter,但它不知道大小,因此我必须在许多计算中使用这两个接口。 C是一个专门的模拟实现前者2.
编辑: 我重写了这个问题,也许它现在真的有意义了。
答案 0 :(得分:1)
我会说明我在评论中提出的观点。在兄弟姐妹之间施放是完全合法的,只要实际对象来自两者。
#include<iostream>
using namespace std;
struct A{
virtual int auu() { return 41; }
};
struct B{
virtual int boo() { return 43; }
};
struct C : public A, public B{
int auu() { return 20; }
int boo() { return 22; }
};
void take_B(B* bp)
{
cout << bp->boo() << endl; // expected
cout << "(The base class would say "
<< bp->B::boo() << ")" << endl; // base class implementation
A *ap = dynamic_cast<A*>(bp);
if(!ap)
{
cerr << "weird, this cast should be possible!" << endl;
}
else
{
cout << ap->auu() << endl; // should work
cout << "(The base class would say "
<< ap->A::auu() << ")" << endl; // base class implementation
}
}
int main()
{
C c;
take_B(&c);
cout << endl << "... and again:" << endl;
// just to clarify: The actual pointer type is irrelevant.
B *bp = &c;
take_B(bp);
return 0;
}