gpt4 book ai didi

c++ - 在类中对多个函数使用指针 C++

转载 作者:行者123 更新时间:2023-11-28 07:20:54 24 4
gpt4 key购买 nike

所以我有 2 个函数和 1 个类。使用 1 个函数,我想设置存储在一个类中的整数的值。对于其他功能,我想再次使用这些值。我正在使用指针,因为我认为这将保存在整个程序的内存地址中。

#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 完成后调用了析构函数。那我该怎么做呢?

最佳答案

你需要将你的 tommymain() 传递给你的每个函数,而不是每次都创建一个新的,否则你只会丢失新的您在函数中创建的 Testclass 对象,实际上会因为您使用 new 而导致内存泄漏。

类似于:

void Function1(TestClass * tommy) {
int randomvalue =2;
tommy->SetValue(randomvalue);
}

然后在 main() 中:

int main() {
TestClass *tommy = new TestClass;
Function1(tommy);
std::cout << tommy->GetValue() << std::endl; // Outputs 2
delete tommy;
return 0;
}

不过,这是一个奇怪的用例 - 这是您希望成员函数执行的操作。这样会更好:

int main() {
TestClass *tommy = new TestClass;
tommy->SetValue(2);
std::cout << tommy->GetValue() << std::endl; // Outputs 2
delete tommy;
return 0;
}

无需 Function1()Function2()。无论哪种方式,您都必须修复:

private:
*value;

在你的类里面,正如其他人指出的那样。

关于c++ - 在类中对多个函数使用指针 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com