c++指针超出作用域

C++ pointer out of scope

本文关键字:作用域 指针 c++      更新时间:2023-10-16

我试图寻找一个答案,但我找不到一个。我是c++新手,所以指针对我来说还不是很直观。

我有一个程序,它有一个main和其他独立的功能,当GUI上的一个按钮被点击时运行。

编译时,我从clickbutton函数得到一个错误,该函数声明指针未声明。我知道这是一个范围问题,但我不知道如何处理这个问题。我知道这是一个非常简单的答案,但我似乎在网上找不到。请告诉我正确的访问方式。

int main () {
...
Contract contract;
contract.firstvalue = 1 // various variables that need to be set for this class
contract.secondvalue = 2 // various variables that need to be set for this class
Contract *pointer = &contract; //pointer
...
}

点击按钮
void clickbutton(){
//clicking a button should change the contract values
pointer.firstvalue = 5;
}
void clickbutton2(){
//clicking a button should change the contract values
pointer.secondvalue = 10;
}
编辑:好吧,我知道我做错了什么。我对main之外的声明感到困惑,因为我无法设置"firstvalue"answers"secondvalue"。然而,我可以在main中设置它们,并在main之外声明变量。在这种情况下,我不需要指针。

在main()之外声明这些变量,当且仅当按钮的代码在同一作用域中。否则,将它们声明为静态,但看看它的作用。

更新:好的。既然您已经修复了原始错误,那么clickbutton()产生错误的原因是因为pointer变量不在范围内。

您将需要如下内容:

void clickbutton(Contract *pointer){
  //clicking a button should change the contract values
  pointer->firstvalue = 5;
}

或者,如果你的合约是一个全局对象(总是存在),

Contract *pointer;
void clickbutton() {
  pointer->firstvalue = 5;
}
int main() {
  Contract c;
  pointer = &c;
  clickbutton();
}

但这可能不是你想要的。

你应该修改你的函数,使它们接受你想要使用的指针作为参数。听起来像是要使用全局变量,如果可能的话应该避免使用。传递对象(如下图所示)是一个更好的主意。注意,此处使用的是箭头->操作符,而不是点.操作符,因为我们处理的是指针。

void clickbutton(Contract *pointer) {
    //clicking a button should change the contract values
    pointer->firstvalue = 5;
}
void clickbutton2(Contract *pointer) {
    //clicking a button should change the contract values
    pointer->secondvalue = 10;
}