处理构造函数的condtional参数

Tia*_*642 0 c++ constructor

我的程序以这种方式工作:如果用户输入数据路径参数,它将使用该路径.如果不是,它使用程序的当前路径.

构造函数是Server(QString path).

显然,这不起作用:

if(!isDefaultPath)
   Server server(userPath);
else
   Server server(programPath);
server.doSmth();
Run Code Online (Sandbox Code Playgroud)

目前,我喜欢这个

Server serverDefault(programPath);
Server serverCustomized(userPath);
if(!isDefaultPath)
       serverCustomized.doSmth();
    else
       serverDefault.doSmth();
Run Code Online (Sandbox Code Playgroud)

但我觉得这不好.有没有更好的方法来做到这一点?

Pet*_*etr 5

最明显的方式是

Server server(isDefaultPath? programPath : userPath )
Run Code Online (Sandbox Code Playgroud)

还要注意,即使你有一个更高级的逻辑不适合一个简单的?:运算符,你总是可以实现它来找到所需的参数作为字符串,然后才初始化构造函数:

path = programPath;
if (....) path = ...
else ...
path = path + ...;

Server server(path);
Run Code Online (Sandbox Code Playgroud)

如果构造函数调用完全不同,则使用指针

std::unique_ptr pServer;
if (...) pServer = std::make_unique<Server>(new Server("a", "b"));
else pServer = std::make_unique<Server>(new Server(137));
Server server = *pServer;
...
Run Code Online (Sandbox Code Playgroud)