简体   繁体   English

虚函数

[英]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: 几件事:

  1. Write foo() and not foo(void) ... the latter is unnecessary and not idiomatic C++ (it is C-like syntax). foo()而不是foo(void) ...后者是不必要的,而不是惯用的C ++(它是类C语法)。
  2. Don't write 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. ,因为已经声明了一个类型。
  3. You should return from a function that doesn't return void (add return 0 ). 您应该从不返回void的函数返回(添加return 0 )。
  4. Your code never frees 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); .
  5. The compile-time type (declared type) of 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()
  6. Either use a declared type of 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM