我需要从堆栈创建一个类实例,但根据变量,我需要使用不同的构造函数调用它
class A
{
public:
A(std::string str);
A(int value)
};
void main(void)
{
bool condition = true;
A class_a {condtion ? "123" : 456};
}
但我无法编译它。
最佳答案
三元运算符不能为 true
和 false
返回不同的类型。
你可以这样解决:
A class_a = condition ? A("123") : A(456);
其他修复:
#include <string>
class A {
public:
A(std::string str) {} // the function must have an implementation
A(int value) {} // the function must have an implementation
};
int main() { // not void main
bool condition = true;
A class_a = condition ? A("123") : A(456);
}
关于c++ - 如何使用不同的构造函数从堆栈实例化一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69864982/