【发布时间】:2009-12-18 22:12:19
【问题描述】:
我正在尝试掌握指针及其出色之处以及更好的 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;
}
【问题讨论】:
-
它实际上可以编译,对吧?它在运行时崩溃。
-
感谢大家的快速响应!
-
作为参考,请记住,任何时候处理指针时,都需要在某处分配内存。如果你在堆栈上分配它,你可以使用一个指向你的局部变量的指针,直到你的方法返回,如果你在堆上分配它,你可以随意使用它,但记得在某个地方释放它。定义或传递指针永远不会分配它指向的对象。