[英]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.