gat*_*tor 0 c++ virtual abstract-class c++03
#include <vector>
class M {
public:
M(unsigned int);
unsigned int n;
};
M::M(unsigned int i) { n = i; }
class A {
protected:
char t;
public:
virtual ~A();
virtual std::vector<M> foo(unsigned int);
char getChar();
};
A::~A(){}
std::vector<M> A::foo(unsigned int u) {
std::vector<M> v;
return v;
}
char A::getChar() { return t; }
class B : public A {
public:
B();
std::vector<M> foo(unsigned int);
};
B::B() { t = 'b'; }
std::vector<M> B::foo(unsigned int c) {
std::vector<M> v;
for (unsigned int i = 0; i < c; i++) {
v.push_back(i);
}
return v;
}
int main() {}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我unused parameter 'u'在A::foo(). 但是,完全删除该函数后,我收到一条错误消息,指出存在对A::foo()from的未定义引用B。B正在实现虚方法并且在 中找不到对定义的引用A,但是A如果预期行为是派生类将始终覆盖基类,换句话说,A::foo()永远不会被调用,为什么需要定义它?
为了更具声明性,有没有办法在基类中声明虚方法但只在派生类中定义它?考虑基本方法调用永远不会显式发生。
您正在寻找的称为“纯虚函数”,并且您在类定义中声明它= 0:
class A {
protected:
char t;
public:
virtual ~A();
virtual std::vector<M> foo(unsigned int) = 0; // <--
char getChar();
};
Run Code Online (Sandbox Code Playgroud)
您可以在 cppreference.com 上阅读有关纯虚函数及其效果的更多信息。
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |