繁体   English   中英

在派生的 object 上调用基础 function

[英]calling a base function on a derived object

class base{
   public:
   virtual void foo(){
     std::cout << "base::foo was called" << std::endl;;
   }
 
   void bar(){
     foo();
     std::cout << "base::bar was called" << std::endl;;
   }
};

class derived : public base {
  public:
  void foo() {
    std::cout << "derived::foo was called" << std::endl;
  }
};

int main() {
    derived der;
    der.bar();
    // desired output = "base::foo was called" "base::bar was called"
    // actual output = "derived::foo was called" "base::bar was called"

}

我在这里遗漏了一些明显的东西吗?
Why does the bar() function when called on an object of derived class call the derived::foo function, even though the function itself only exists in the base class.

base::foo被声明为virtual ,因此使用虚拟调度。 如果您不希望这样,请显式调用base::foo

struct  base{
   virtual void foo(){
     std::cout << "base::foo was called" << std::endl;;
   }
 
   void bar(){
     base::foo();
     std::cout << "base::bar was called" << std::endl;;
   }
};

(请注意,在您的示例中,所有方法都是私有的,我想这只是一个错字)

When a member function in a derived class overrides a virtual member function in a base class like this, that means it entirely replaces the function definition for most purposes. 因此,在main中创建的 object der上调用 function foo通常将使用Derived::foo定义。 无论调用foo的代码是在Derived的成员中,还是在Base的成员中,或者两者都不是 class,此行为都是一致的。

两个主要的例外是:

  1. 如果您使用“qualified-id” class_type::func_name语法来调用 function,这将禁用虚拟 function 逻辑,并且只调用 ZC1C425268E68385D14AB5074C17A 重载解析您命名的 ZC1C425268E68385D14AB5074C17A 重载Z9。

因此,既然您说您希望程序调用base::foo ,请将base::bar更改为:

void bar() {
    base::foo();
    std::cout << "base::bar was called" << std::endl;
}
  1. 在基 class 的构造函数或析构函数期间,基 class(或其基之一)中的 function 将被调用,忽略派生类中的覆盖器。 object 被认为还不是或不再是派生类型的 object。 (如果派生的 function 被调用并使用任何尚未创建或已销毁的派生成员,这将很麻烦。)

When you declare a function virtual , the compiler will generate a vtable for each object created, and in your case, since the object is a derived the function vtable will always point to derived::foo() for that instance.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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