简体   繁体   中英

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:

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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM