虚函数的继承
Inheritance of a Virtual Function
我有以下一段代码。
class A {
public:
virtual void foo() = 0;
}
class B : public A {
public:
void bar() { /* Do something */ }
}
void B::A::foo() {
bar();
// Do something else
}
当我尝试编译这个时...我收到一个错误,说它找不到bar()
。这不是实例化纯虚函数的正确方法吗?
use of undeclared identifier 'bar'
void B::A::foo()
没有多大意义。看起来你的意思是在B
中实现foo()
,为此你需要在B
的类声明中声明它,然后实现它:
class B : public A {
public:
void foo();
void bar() { /* Do something */ }
};
void B::foo() {
bar();
// Do something else
}
由于以下几个原因,您的代码将无法编译:
class A
{
public:
virtual void foo() = 0; // this defining a pure virtual function - making A an abstract class
}; // missing ; here
class B : public A
{
public:
void bar() { /* Do something */ }
// you never implement foo, making B another abstract class
}; // again with the ;
void B::A::foo() // this line makes no sense
{
bar();
// Do something else
}
我相信您要做的是以下内容
class A
{
public:
virtual void foo() = 0;
};
class B : public A
{
public:
virtual void foo() { bar(); } // override A::foo
void bar() { /* Do something */ }
};
如果要重写函数,则必须将其声明为已重写。 如果从抽象基类派生类并且未实现其函数,则派生类也是抽象基类。 在实例化任何类之前,其所有函数都必须是非抽象的。
相关文章:
- 继承函数的重载解析
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 派生类调用使用非继承成员的继承函数
- 继承函数是否适用于 C++ 中的基类元素或派生类元素?
- 在链表中的某个点插入时出现问题,C++中的继承函数
- std :: is_same-来自integral_constant的继承函数的用例
- 如何将同名的继承函数视为重载函数
- 使用子函数的继承函数
- 执行覆盖的继承函数
- 相对于更专业的继承函数,模板更喜欢子类函数
- C++:继承函数并重新定义它们
- C++ 继承函数指针,可与派生方法一起使用
- 不同对象的向量,对象具有非继承函数
- C++多级继承函数调用
- 基类指向派生类继承函数调用的指针
- C++继承函数覆盖
- 派生类是否C++必须在头文件中包含继承函数/成员的定义
- 继承函数中的参数消失
- C++通过继承函数实现继承的抽象函数
- 构造函数和继承函数 c++