C++通过 const 引用传递时不调用派生类函数

C++ not calling derived class function when passing by const reference

本文关键字:调用 派生 类函数 通过 const 引用 C++      更新时间:2023-10-16

以下是我的代码摘要:

基类:

#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(); }