所以我有2个函数和1个类。带有1个函数的 我想设置存储在类中的整数的值。与其他函数 我想再次使用这些值。 我正在使用指针,因为我认为这将保存在整个程序的内存地址上。在多个函数中使用类中的指针C++
#include <iostream>
using namespace std;
void Function1();
void Function2();
class TestClass
{
public:
TestClass();
~TestClass();
void SetValue(int localValue)
{
*value = localvalue;
}
int GetValue()const
{
return *value;
}
private:
*value;
};
TestClass::TestClass()
{
value = new int(0);
}
TestClass:
~TestClass()
{
delete value;
}
int main()
{
TestClass *tommy = new TestClass; //this didn't work,
//couldn't use SetValue or Getvalue in functions
Function1();
Function2();
return 0;
}
void Function1()
{
int randomvalue = 2;
TestClass *tommy = new TestClass; //because it didnt work in main, i've put it here
tommy->SetValue(randomvalue);
}
void Function2()
{
TestClass *tommy = new TestClass;
cout << tommy->GetValue();
<< endl; //this gave a error, so I put the above in again
//but this returns 0, so the value isn't changed
}
那么,给我一个解决方案?我没有收到任何编译错误,但值没有改变,可能是因为在Function1完成后调用了析构函数。那我该怎么做呢?
请更具体一些。什么没有工作?您是否收到错误消息(如果是这样,请发布)?你有没有得到意想不到的行为(如果是这样,描述它)? –
你有没有听过缩进。使事情易读 –