我正在构建一个接口,使用单独的变量访问单独的接口会有点不方便,如果我能以某种方式创建两者的联合,那将是伟大的。
在文件中:
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无关的继承层次结构。
可能答案是否定的,但是我很好奇这样的想法是否来自语言开发人员,因为在我的原始思维中,这并不是一个牵强的想法。
编辑:实际上,A和B是抽象的。A是一个Simulation对象,它有size()和length()这样的方法。B是一个IO接口,实现getter和setter,但它不知道大小,所以我必须在许多计算中使用这两个接口。C是实现前2种方法的专用仿真。
编辑:我重写了这个问题,也许现在它真的有意义了。
我将说明我在评论中提出的观点。在兄弟对象之间进行强制类型转换是完全合法的,只要实际对象是从两个对象派生而来。
#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;
}