我想弄清楚指針和它們的迷人性以及更好的C++理解。我不知道爲什麼這不會編譯。請告訴我什麼是錯的?我想在創建類的實例時初始化指針。如果我嘗試用正常的詮釋它工作正常,但是當我試圖用指針設置它我得到這個在控制檯Newb C++類問題
運行...
構造稱爲
程序接收到的信號:「 EXC_BAD_ACCESS」。
sharedlibrary應用負載規則所有
任何幫助是極大的讚賞。
下面是代碼
#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;
}
它實際上編譯,對吧?它在運行時崩潰。 – 2009-12-18 22:26:09
你是對的先生。 – 2009-12-18 22:32:06
感謝大家和你的快速回復! – 2009-12-18 22:34:06