gpt4 book ai didi

c++ - 我可以调用虚函数来初始化基类子对象吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:34:35 30 4
gpt4 key购买 nike

我知道不应该在构造函数中直接或间接调用虚函数,但这段代码运行良好。
我这里的东西安全吗?

#include <iostream>
#include <string>

struct A {
A (const std::string& name) {std::cout << name << std::endl;}
virtual std::string tag() const = 0;
};

struct B: A {
B() : A (tag()) {}
virtual std::string tag() const override {return "B";}
};

int main() {
B b; // Output gives "B\n"
}

如果不是,以下(基于评论)是否是正确的解决方法?

// Replacement for class B:

struct B: A {
B() : A (name()) {}
virtual std::string tag() const override {return name();}
private:
static std::string name() {return "B";} // use static function
};

最佳答案

在构造函数和/或析构函数中调用虚拟成员通常是可以的。

不过,在初始化所有基之前,在 ctor 初始化器中这是一个不同的游戏:

12.6.2 Initializing bases and members [class.base.init]

[...]
14 Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined.

关于c++ - 我可以调用虚函数来初始化基类子对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25754796/

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