[英]common function in base and derived calling base when called through another base function using a derived object?
[英]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,此行为都是一致的。
两个主要的例外是:
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;
}
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.