简体   繁体   English

C++ 如何根据作为输入传递的参数调用一个或另一个构造函数?

[英]C++ How can I call one constructor or the other depending on the parameters passed as input?

I have these two constructors:我有这两个构造函数:

MyClass(char* path);
MyClass(int n);

and I need to call the first if the user has passed the path as an argument, the other otherwise.如果用户将路径作为参数传递,我需要调用第一个,否则调用另一个。

My problem is that I don't know how to do this since I can't define the class without initialising it first, nor can I define a reference and then create the class into an if-else block like this:我的问题是我不知道如何执行此操作,因为我无法在不先初始化 class 的情况下对其进行定义,也无法定义引用然后将 class 创建到这样的 if-else 块中:

MyClass& c;
if (argc == n) // path passed
{
    c = MyClass(argv[n-1]);
}
else {
    c = MyClass(10);
}

You can use a ternary expression.您可以使用三元表达式。 (Before C++17, this requires that your class is copyable or movable.) (在 C++17 之前,这要求您的 class 是可复制或可移动的。)

MyClass c = argc == n ? MyClass(argv[n-1]) : MyClass(10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C ++如何从具有一个参数的派生类构造函数调用具有两个参数的超类构造函数? - C++ How can I call superclass constructor with two parameters from derived class constructor with one parameter? 根据传递给构造函数的参数,C++ 方法是否可以具有不同的返回类型? - Can a C++ method have different return types depending on parameters passed to the constructor? 如何在C ++构造函数中验证输入参数? - How to validate input parameters in C++ constructor? C ++:可以使用具有相同参数的私有构造函数重载构造函数吗? - C++: Can one overload a constructor with a private constructor with the same parameters? 如何根据用户输入声明 C++ 构造函数? - How to declare a C++ constructor depending on user input? 如何在main()c ++中调用构造函数? - How can I call a constructor in main() c++? 如何在C ++中调用可变参数模板构造函数? - How can I call variadic template constructor in c++? 理论上可以在c ++函数中将多少个参数作为参数传递? - How many arguments can theoretically be passed as parameters in c++ functions? 构造函数可以在c ++中调用另一个构造函数吗? - Can constructor call another constructor in c++? 使用初始化列表时检查传递给构造函数的参数-C ++ - Check parameters passed to constructor when using initialization lists - C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM