2009-12-18 33 views
1

我想弄清楚指針和它們的迷人性以及更好的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; 
} 
+0

它實際上編譯,對吧?它在運行時崩潰。 – 2009-12-18 22:26:09

+0

你是對的先生。 – 2009-12-18 22:32:06

+0

感謝大家和你的快速回復! – 2009-12-18 22:34:06

回答

10

你永遠不要創建INT的指針指向,所以指針指向的內存沒有按面積」 t存在(或用於別的東西)。

您可以使用new從堆中獲取內存塊,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; 
} 
+1

不錯的答案(+1),但你的第二個代碼塊應該是析構函數而不是第二次構造函數。 – Kevin 2009-12-18 22:45:39

4

你只是缺少一個新的,在構造函數中。

itsTenure = new int; 

但是,您不需要將它作爲指針。你爲什麼?

1

您需要爲分配內存*任期在構造函數中:

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

你要分配的內存塊的INT刪除它,然後才使用這塊內存的地址(指針)。這與new完成:

cout << "Destructor called \n"; 
itsTenure = new int;  
*itsTenure = 0; 

然後,你必須用delete釋放在析構函數的內存:

cout << "Destructor called \n"; 
    delete itsTenur; 
3

*itsTenure = 0不初始化指針。它將0寫入到其tenTure指向的位置。既然你從來沒有指定過它指向的地方,那可能在任何地方,行爲也是未定義的(像你這樣的訪問違規成爲最可能的結果)。

+0

+1用於解釋*爲什麼*需要分配int。 – 2009-12-18 22:33:07