c++指针超出作用域
C++ pointer out of scope
我试图寻找一个答案,但我找不到一个。我是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;
}
相关文章:
- 全局作用域中函数指针的赋值
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 如何从类函数返回指向类作用域数组的指针?
- 块作用域中的函数指针定义
- c++ 指针在离开作用域后不会停留
- 混合指向已分配对象和作用域对象的指针
- 在一个作用域中推送五个对象指针,然后检查对象的布尔值是否为 false,会给出错误
- 空的唯一指针在离开作用域时调用析构函数
- 使用作用域内生成的指针初始化静态成员
- 提升::进程间managed_shared_memory指针有效作用域
- 什么是C++中的作用域指针
- 在释放了所有作用域内指针之后仍然可访问内存
- C++指针到指针作用域的问题
- 模板类中静态函数或指针的作用域解析
- 有没有一种方法可以通过使用指针来处理作用域
- 关于 C++(或 C)中的指针的函数作用域
- Boost作用域指针指向Boost线程
- 当类没有析构函数时,智能指针或作用域指针会删除对象吗
- 如何在作用域指针类中正确使用动态分配的不透明指针
- 如何传递作用域指针而不是this指针