查看我提供的代码,我试图使其成为z = x
但是它不起作用,因为x在另一个函数中。一直说x没有被声明。有什么办法可以解决这个问题?
class game{
public:
void Starter(){
string z {"Test"};
z = x;
}
private:
void Questions(){
string x;
cout << "Welcome to this game, please answer with yes or no: \n \n";
您需要将x
传递到z
。
void Starter(string x){
string z {"Test"};
z = x;
}
然后您可以在其他功能中执行Starter(x);
您不应该从另一个方法访问一个方法的自动变量。造成这种情况的原因有很多:最明显的是,此变量始终是新变量,并且在退出函数后仍未激活。在您的情况下,这些方法不会相互调用,因此z
和x
的生存期甚至不会重叠。
您可能需要一个可以从两个函数中看到的持久变量。有多种选择供您选择:对象字段,全局变量,静态成员...
您的代码未描述您的意图,但是我想您的正确选择是数据成员:
class game{
public:
void Starter(){
string z {"Test"};
z = x; // You can access x here because it is a data member `this->x`;
}
private:
string x;
void Questions(){
cout << "Welcome to this game, please answer with yes or no: \n \n";
// Do whatever you want with x
}
};