声明变量,其类型具有删除的默认构造函数,没有值

Jos*_*ler -1 c++ default-constructor variable-declaration

我想在多个 if-else 分支中初始化一个变量,稍后使用它,基本上是这样的:

Foo foo;

if (someCondition) {
    std::string someString = getTheString();
    // do some stuff
    foo = Foo(someString);
} else {
    int someInt = getTheInt();
    //do some other stuff maybe
    foo = Foo(someInt);
}

// use foo here
Run Code Online (Sandbox Code Playgroud)

不幸的是,在这个例子中,类型Foo有一个删除的默认构造函数,所以上面的代码不能编译。有没有办法以这种方式初始化这样的变量?

编辑:

正如您在我的示例中看到的那样,我使用了不同的构造函数,并且还在 if/else 块中执行了其他操作,因此不幸的是,三元运算符不起作用。
如果没有办法,没有foo指针,我显然可以采取不同的方法,但我很好奇,如果我的方法以某种方式起作用。

Ðаn*_*Ðаn 5

你还没有告诉我们你为什么不能使用指针......但是,与此同时,这里有一个表面上是无指针的解决方案:

#include <optional>    
std::optional<Foo> foo;

if (someCondition) {
    std::string someString = getTheString();
    // do some stuff
    foo.emplace(someString);
} else {
    int someInt = getTheInt();
    //do some other stuff maybe
    foo.emplace(someInt);
}
if (foo.has_value()) { /* use foo here */ }
Run Code Online (Sandbox Code Playgroud)

如果您有编码标准或禁止使用原始指针(和new)的内容,那么您可以使用std::unique_ptr.

#include <memory>
std::unique_ptr<Foo> foo;

if (someCondition) {
    std::string someString = getTheString();
    // do some stuff
    foo = std::make_unique<Foo>(someString);
} else {
    int someInt = getTheInt();
    //do some other stuff maybe
    foo = std::make_unique<Foo>(someInt);
}
if (foo) {/* use foo here */}
Run Code Online (Sandbox Code Playgroud)

您还可以将Foo-creation 逻辑放在单独的函数(或 lambda)中:

auto getFoo(/* ... */) {
    if (someCondition) {
        std::string someString = getTheString();
        // do some stuff
        return Foo(someString);
    } else {
        int someInt = getTheInt();
        //do some other stuff maybe
        return Foo(someInt);
   }
}
// ...
Foo foo = getFoo(/*...*/);
// use foo here
Run Code Online (Sandbox Code Playgroud)