c++ - 如何使用不同的构造函数从堆栈实例化一个类?

标签 c++ c++11

我需要从堆栈创建一个类实例,但根据变量,我需要使用不同的构造函数调用它

  class A
    {
     public:
      A(std::string str);
      A(int value)
    };

void main(void)
{
 bool condition = true;

 A class_a {condtion ? "123" : 456};
   
}

但我无法编译它。

最佳答案

三元运算符不能为 truefalse 返回不同的类型。

你可以这样解决:

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/

相关文章:

c++ - Qt Widget应用程序 "Library not registered"错误

c++ - 为什么对同一模板参数的不同参数会有这样的要求?

c++ - 不完整类型 struct std::hash 与 unordered_map 的无效使用,其中 std::pair of enum class 作为键

C++11内存模型: why can't compiler move statements across load() operations during optimization?

function - 将 std::function 添加到向量 c++

c++ - OpenCL : different work kernel code for the x86 and x64 versions

c++ - 尝试打印 3 种类型的时间 : universal, 标准和军用(3 个文件)

c++ - 重载 >> 运算符

c++ - 将多个参数传递给 _beginThreadEx

c++ - 监控 C++11 和 C++03 中的类实现?