我有以下抽象类
class A {
public:
virtual void foo(A* a) = 0;
}
以及从这个类继承的几个类。例如
class B : public A {
public:
void foo(A* a); // implementation in a separete file
}
但是,我只希望 classB
接受自己作为参数foo
void foo(B* b);
是否可以在 C++ 中做到这一点?我考虑过一个模板,但语法允许太多的灵活性。可以写class B: public A<B>
,但我想要一个编译器错误class B: public A<C>
。
- 编辑 -
似乎我对抽象类的使用是不合理的。让我澄清一下我的情况。
我A
在一个单独的函数中使用了多态行为。除此之外,我想定义一个函数,它接受一个相同类型的参数,比如上面的那个。我正在尝试编写一个函数来定义派生类的两个对象之间的距离。距离仅在来自同一类的对象之间定义(b1
and b2
, or c1
and c2
,但不是b1
and c2
)。我也想以尽可能通用的方式访问这个距离函数。
-- 编辑 2--
Cássio 展示了为什么不能执行基于编译器的检查。zar 的解决方案通过运行时错误检查为代码添加了更多结构。
我知道您的问题更多是关于语法的。你所拥有的是对的,只需传递一个类型 B 的对象。定义仍然会说 A,但它会很乐意接受派生类。您不需要对此有任何特殊定义。
class A {
public:
virtual void foo(A* a) = 0;
};
class B : public A {
public:
void foo(A* a)
{
if (dynamic_cast<B*> (a) == NULL)
std::cout << "wrong type, expecting type B\r\n";
}
};
class C : public A {
public:
void foo(A* a)
{
if (dynamic_cast<C*> (a) == NULL)
std::cout << "wrong type, expecting type C\r\n";
}
};
int main()
{
B * b1 = new B;
B * b2 = new B;
C * c1 = new C;
C * c2 = new C;
b2->foo(c1); // bad
c1->foo(b1); // bad
b2->foo(b1); // good
delete b1;
delete b2;
delete c1;
delete c2;
}
另见dynamic_cast。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句