嘿,我想在故事情节中使用函数wolves变量,我正在尝试这样做:

"\nYou awake on a beach to the sound of"<< Wolves().name; " starving and blood hungry,"
        "\nThere is a Rock on the ground.  You pick it up";
        inventory.push_back("Rock");


但是Wolves()。name;标题中提到了错误。我为什么不能这样做?

这是功能狼的代码:

void Wolves()
{
    string name = "Wolves";
    int health = 20;
    hitPoints() +1;
}

最佳答案

您不能从C ++中的函数外部访问函数中定义的变量,但可以将其更改为类:

class Wolves {
  public:
    string name;
    // ...

    Wolves(); // Constructor
    //...
}


要访问它,您可以使用

Wolves wolve;
wolve.name = "whateverName"; // or set it in the constructor
cout << wolve.name << endl;

关于c++ - 无法使用函数变量?错误表达式必须具有类类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12770475/

10-11 18:17