Newb C++类问题

Cra*_*ows 1 c++ pointers class

我试图掌握指针和它们的精彩以及更好的C++理解.我不知道为什么这不会编译.请告诉我有什么问题?我正在尝试在创建类的实例时初始化指针.如果我尝试使用普通的int它可以正常工作但是当我尝试用指针设置它时我会在控制台中得到它

正在运行...

构造函数调用

程序接收信号:"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;
}
Run Code Online (Sandbox Code Playgroud)

Yac*_*oby 10

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

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

itsTenure = new int;
Run Code Online (Sandbox Code Playgroud)

所以现在itsTenure保存内存位置,你可以取消引用它来设置它的值.

更改的构造函数如下:

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

但您还必须记得使用删除它 delete

Agents::~Agents()
{
    cout << "Destructor called \n";
    delete itsTenure;
}
Run Code Online (Sandbox Code Playgroud)