gpt4 book ai didi

c++ - Newb C++类问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:05:24 25 4
gpt4 key购买 nike

我正在努力掌握指针及其强大之处,同时更好地理解 C++。我不知道为什么这不会编译。请告诉我哪里出了问题?我试图在创建类的实例时初始化指针。如果我尝试使用普通的 int 它工作正常但是当我尝试使用指针设置它时我在控制台中得到了它

Running…

Constructor called

Program received signal: “EXC_BAD_ACCESS”.

sharedlibrary apply-load-rules all

非常感谢任何帮助。

这是代码

#include <iostream> 
using namespace std;
class Agents
{
public:
Agents();
~Agents();
int getTenure();
void setTenure(int tenure);
private:
int * itsTenure;
};
Agents::Agents()
{
cout << "Constructor called \n";
*itsTenure = 0;
}
Agents::~Agents()
{
cout << "Destructor called \n";
}
int Agents::getTenure()
{
return *itsTenure;
}
void Agents::setTenure(int tenure)
{
*itsTenure = tenure;
}
int main()
{
Agents wilson;
cout << "This employees been here " << wilson.getTenure() << " years.\n";
wilson.setTenure(5);
cout << "My mistake they have been here " << wilson.getTenure() <<
" years. Yep the class worked with pointers.\n";
return 0;
}

最佳答案

您永远不会创建指针指向的 int,因此指针是指向不存在(或用于其他用途)的内存区域的指针。

可以使用new从堆中获取一 block 内存,new返回内存位置的地址。

itsTenure = new int;

现在 itsTenure 保存了内存位置,您可以取消引用它以设置它的值。

修改后的构造函数如下:

Agents::Agents()
{
cout << "Constructor called \n";
itsTenure = new int;
*itsTenure = 0;
}

但您还必须记住使用 delete

删除它
Agents::~Agents()
{
cout << "Destructor called \n";
delete itsTenure;
}

关于c++ - Newb C++类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1930974/

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