[英]Virtual function
class a
{
virtual void foo(void) ;
};
class b : public a
{
public:
virtual void foo(void)
{
cout<< "class b";
}
};
int main ( )
{
class a *b_ptr = new b ;
b_ptr->foo();
}
please guide me why the b_ptr->foo() will not call the foo() function of the class b? 请指导我为什么b_ptr-> foo()不会调用类b的foo()函数?
As you've written the code, it won't compile due to access control violations. 在编写代码时,由于访问控制违规,它将无法编译。 Since
b_ptr
is actually of type a *
and a::foo
is private, the compiler won't allow that. 由于
b_ptr
实际上是a *
类型而a::foo
是private,因此编译器不允许这样做。
But make a::foo
public and that will correctly call b::foo
. 但是让
a::foo
公开,这将正确调用b::foo
。
There is also the problem that you have not defined a::foo
so your program won't link. 还有一个问题是你没有定义
a::foo
所以你的程序不会链接。 You need to either define it or make it pure virtual (ie virtual void foo(void) = 0;
). 您需要定义它或使其成为纯虚拟(即
virtual void foo(void) = 0;
)。
因为a:foo()不公开。
Several things: 几件事:
foo()
and not foo(void)
... the latter is unnecessary and not idiomatic C++ (it is C-like syntax). foo()
而不是foo(void)
...后者是不必要的,而不是惯用的C ++(它是类C语法)。 class
in a* b_ptr = new b;
a* b_ptr = new b;
写class
a* b_ptr = new b;
, since a's type has already been declared. return 0
). return 0
)。 b_ptr
. b_ptr
。 It would be better to write std::auto_ptr<a> b_ptr(new b);
std::auto_ptr<a> b_ptr(new b);
会更好std::auto_ptr<a> b_ptr(new b);
. b_ptr
is a*
while it's runtime type (instantiation/allocation type) is b*
. b_ptr
的编译时类型(声明的类型)是a*
而它的运行时类型(实例化/分配类型)是b*
。 The compiler (and the type system) only know about compile time types, and so checks for access privileges are performed based on compile-time type... hence b_ptr->foo()
isn't allowed. b_ptr->foo()
。 b*
or make a::foo
public to use it in the way you wish. b*
类型或使a::foo
public以您希望的方式使用它。 Make that 做那个
class a
{
public:
virtual void foo(void);
};
You can't override a private function.
您无法覆盖私有函数。
Though I'm not sure how you managed to call b_ptr->foo()
anyways since a::foo
is private. 虽然我不确定你是怎么设法调用
b_ptr->foo()
因为a::foo
是私有的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.