C++通过 const 引用传递时不调用派生类函数
C++ not calling derived class function when passing by const reference
以下是我的代码摘要:
基类:
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "Base constructor" << endl; }
~Base() { cout << "Base destructor" << endl; }
virtual void func(void) const { cout << "base" << endl; }
};
派生类:
#include "Base.h"
class Derived : public Base {
public:
Derived() { cout << "Derived constructor" << endl; }
~Derived() { cout << "Derived destructor" << endl; }
void func(void) const { cout << "derived" << endl; }
};
测试类:
#include "Derived.h"
class Test {
public:
const Base& base;
Test(const Base& _base) : base(_base) { cout << "Test constructor" << endl; }
void test() { base->func(); }
~Test() { cout << "Test destructor" << endl; }
};
测试的主要功能:
#include "Test.h"
int main(void) {
Test* t = new Test(Derived());
t->test();
return 0;
}
当我运行 main 函数时,正在调用func的基本版本。
但是,如果我将主函数更改为以下内容:
#include "Test.h"
int main(void) {
Derived d;
Test* t = new Test(d);
t->test();
return 0;
}
正确调用了func的派生版本。 我还尝试将测试中的const Base&base更改为Base*base。然后使用
Test* t = new Test(new Derivec())
事实证明,函数的派生版本也被正确调用。
我在想,如果我使用引用或指针,多态性就会起作用。
谁能向我解释为什么第一个版本没有正确调用派生类方法?
非常感谢您的帮助!
您有一个悬而未决的引用问题。
Test* t = new Test(Derived());
您正在使用Derived
类型的临时对象来构造t
。临时对象在Test
的构造函数返回后被删除。
因此,您的程序具有未定义的行为。
如果您使用
Derived d;
Test* t = new Test(d);
您获得预期的行为,因为t
没有悬而未决的引用。
另请注意
void test() { base->func(); }
不应该编译,因为base
是一个参考。该行需要:
void test() { base.func(); }
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 调用派生类成员函数
- 从基类实例调用派生类方法而不进行强制转换
- 从基类 (C++) 调用派生类中的非虚函数
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何从 Gtk::窗口调用派生对象的析构函数
- 在dynamic_pointer_cast后调用派生类的构造函数
- 从 Base 引用对象调用派生类的成员
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 在 c++ 中,如何使用向量调用派生类?
- C++通过 const 引用传递时不调用派生类函数
- 哪个基类调用派生重写的方法?
- 如何从包含基类指针的容器中调用派生类函数(基于其类型)?
- 如何调用派生类之一
- 从基类数组调用派生函数
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数
- 基类如何调用派生类在 c++ 中传递的闭包?
- 通过在基类中虚拟调用派生类中的函数来访问派生类中的函数
- 如何在另一个类的向量中调用派生类的析构函数
- 通过reinterpret_casting方法指针从指针调用派生类的方法。这是 UB 吗?