相关疑难解决方法(0)

在C++中声明if-else块中的变量

我试图在if-else块中声明一个变量,如下所示:

int main(int argc, char *argv[]) {

    if (argv[3] == string("simple")) {
        Player & player = *get_Simple();
    } else if (argv[3] == string("counting")) {
        Player & player = *get_Counting();
    } else if (argv[3] == string("competitor")) {
        Player & player = *get_Competitor();
    }

    // More code
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编译时,我遇到以下错误:

driver.cpp:38:错误:未使用的变量'
player'driver.cpp:40:错误:未使用的变量'
player'driver.cpp:42:错误:未使用的变量'
player'driver.cpp:45:错误:'player'在这方面没有申明

有任何想法吗?

c++ variables if-statement

6
推荐指数
2
解决办法
1万
查看次数

有条件地调用其他构造函数

我想根据运行时条件调用同一类的不同构造函数。构造函数使用了不同的初始化列表(在之后的一堆东西:),因此我无法在构造函数内处理条件。

例如:

#include <vector>
int main() {
    bool condition = true;
    if (condition) {
        // The object in the actual code is not a std::vector.
        std::vector<int> s(100, 1);
    } else {
        std::vector<int> s(10);
    }
    // Error: s was not declared in this scope
    s[0] = 1;
}
Run Code Online (Sandbox Code Playgroud)

我想我可以使用指针。

#include <vector>
int main() {
    bool condition = true;
    std::vector<int>* ptr_s;
    if (condition) {
        // The object in the actual code is not a std::vector.
        ptr_s = new std::vector<int>(100, 1); …
Run Code Online (Sandbox Code Playgroud)

c++ constructor

6
推荐指数
1
解决办法
2281
查看次数

如何有条件地实例化一个对象?

我正在尝试做一些有条件的工作:

Type object;
if (cond) {
    doSomeStuff();
    object = getObject();
    doMoreStuff();
} else {
    doSomeOtherStuff();
    object = getDifferentObject();
    doEvenMoreStuff();
}
use(object);
Run Code Online (Sandbox Code Playgroud)

我能想到解决这个问题的唯一方法是复制use代码(它实际上是我的应用程序中的内联代码)并objectif块的每个分支中声明。如果我想避免重复代码,我必须将它包装在一些 use 函数中,就像上面一样。在实际情况下,此use函数可能需要 5 个以上的参数来基本上继承上下文。这一切看起来很混乱,无法维护。

if (cond) {
    doSomeStuff();
    Type object = getObject();
    doMoreStuff();
    use(object);
} else {
    doSomeOtherStuff();
    Type object = getDifferentObject();
    doEvenMoreStuff();
    use(object);
}
Run Code Online (Sandbox Code Playgroud)

解决这个问题的最佳方法是什么?Type没有默认构造函数,因此片段 1 无法编译。

其他一些语言支持片段 1 - 相关问题:Forcing uninitialised Declaration of member with a default constructor

c++ optimization class instantiation conditional-statements

3
推荐指数
3
解决办法
139
查看次数