gpt4 book ai didi

构造函数中的 C++ 虚函数

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:45 25 4
gpt4 key购买 nike

我正在阅读 this关于 C++ 构造函数的文章

We recommend that you be careful when you call virtual functions in constructors. Because the base class constructor is always invoked before the derived class constructor, the function that's called in the base constructor is the base class version, not the derived class version. In the following example, constructing a DerivedClass causes the BaseClass implementation of print_it() to execute before the DerivedClass constructor causes the DerivedClass implementation of print_it() to execute:

例子:

    class BaseClass {
public:
BaseClass() {
print_it();
}
virtual void print_it() {
cout << "BaseClass print_it" << endl;
}
};

class DerivedClass : public BaseClass {
public:
DerivedClass() {
print_it();
}
virtual void print_it() {
cout << "Derived Class print_it" << endl;
}
};

int main() {

DerivedClass dc;
}

这是输出:

BaseClass print_it
Derived Class print_it

I tried this code and the output is as stated above .但是,我也尝试了没有 virtual 关键字的相同示例:

    class BaseClass {
public:
BaseClass() {
print_it();
}
void print_it() {
cout << "BaseClass print_it" << endl;
}
};

class DerivedClass : public BaseClass {
public:
DerivedClass() {
print_it();
}
void print_it() {
cout << "Derived Class print_it" << endl;
}
};

int main() {

DerivedClass dc;
}

and got the same result .

那么有什么区别,他们警告的危险是什么?

@标记为重复:

这个问题是不同的,因为构造函数都调用虚方法而不是一个构造函数调用虚方法。

最佳答案

没有区别。 这就是危险。

如果您不知道,那么您可能会期望这样:

Derived Class print_it
Derived Class print_it

期望是存在的,因为如果你从 Base 中的函数调用 virtual print_it(),多态性意味着你通常会得到Derived 版本。

但是,当你写在Base构造函数中时,对象的Base部分还在构造中,而构造中对象的“动态类型”仍然是 Base,而不是 Derived。所以你不会得到通常的多态行为。

这篇文章警告你这个事实。

关于构造函数中的 C++ 虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38665566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com