我有一个基类A和两个从B派生的B,C。方法func的声明在A类中给出。如何为B和C分别定义方法func?
class A {
public:
void func();
};
class B : public A {
//some members
};
class C : public A {
//some members
};
//define B's func here without changing the definition of the three classes
//define C's func here without changing the definition of the three classes
答案 0 :(得分:2)
你必须使你想要覆盖“虚拟”或“纯虚拟”的方法,如果一个类有虚拟方法,那么析构函数也必须是虚拟的:
-
答案 1 :(得分:2)
不,如果没有在类中声明类,则无法实现类的成员函数。
class A {
public:
void func();
};
class B : public A {
//some members
};
class C : public A {
//some members
};
void B::func() {}
void C::func() {}
/tmp/164435074/main.cpp:17:9: error: out-of-line definition of 'func' does not match any declaration in 'B'
void B::func() {}
^~~~
/tmp/164435074/main.cpp:18:9: error: out-of-line definition of 'func' does not match any declaration in 'C'
void C::func() {}
^~~~