【问题标题】:How to instantiate a class from the stack with different constructors?如何使用不同的构造函数从堆栈中实例化一个类?
【发布时间】:2021-12-20 04:50:16
【问题描述】:

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

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

void main(void)
{
 bool condition = true;

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

但我无法编译。

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    三元运算符不能为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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2013-06-14
      • 2014-04-22
      • 1970-01-01
      • 2015-12-04
      相关资源
      最近更新 更多