ssb*_*ssb 0 c++ inheritance virtual-functions c++11 clang++
我有以下代码.
class A {
public:
virtual void foo() = 0;
}
class B : public A {
public:
void bar() { /* Do something */ }
}
void B::A::foo() {
bar();
// Do something else
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译这个...我得到一个错误,说它无法找到bar().这不是实例化纯虚函数的正确方法吗?
use of undeclared identifier 'bar'
Run Code Online (Sandbox Code Playgroud)
jua*_*nza 10
void B::A::foo()没有多大意义.它看起来像你的意思是要实现foo()中B,而您需要声明它B的类声明,然后实现它:
class B : public A {
public:
void foo();
void bar() { /* Do something */ }
};
void B::foo() {
bar();
// Do something else
}
Run Code Online (Sandbox Code Playgroud)
您的代码将无法编译,原因如下:
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
}
Run Code Online (Sandbox Code Playgroud)
我相信你要做的是以下几点
class A
{
public:
virtual void foo() = 0;
};
class B : public A
{
public:
virtual void foo() { bar(); } // override A::foo
void bar() { /* Do something */ }
};
Run Code Online (Sandbox Code Playgroud)
如果要覆盖函数,则必须将其声明为重写.如果从抽象基类派生类并且不实现其函数,则派生类也是抽象基类.在实例化任何类之前,它的所有函数都必须是非抽象的.
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |