1

中初始化一個動態分配的數組,我們應該爲每個索引分配一個空字符串,並用函數addB()中的值替換 。 我很新,所以我有很多麻煩。如何在類構造函數

class A //in a.h 

{ 

    private: 

    B * b; 

    int maxNumberOfItems; 

    //... 

    public: 

    A(); 

    ~A(); 

void addB(const B & something); 

}; 

//in a.cpp 

A::A() 

    { 

    maxNumberOfItems=10; 
    for(int i=0;i<maxNumberOfItems;i++) 
    { 
     b[i]="";//has to be an empty string, I am getting a segmentation fault 
    } 

    } 

    A::~A(){/*...*/} 

    //... 

//in b.h 

class B 
{ 

private: 

     string name; 

     int price; 

    public: 

     void setName(string); 

     string getName(); 

     void setPrice(); 

     int getPrice(int); 

     B & operator=(string &); 

}; 

//in b.cpp 

B & B::operator=(string & a){name = a;price = 0; return *this;} 
//... 

這只是一個顯示我的問題

+0

'b'似乎是一個未初始化的指針......你想知道_how_分配內存嗎? –

+0

你的'b'沒有被分配。閱讀關於[operator new \ [\]](http://en.cppreference.com/w/cpp/memory/new/operator_new) –

+0

房間裏的大象:使用'std :: vector'而不是動態數組,如果可能的話。 – user4581301

回答

3

你應該使用動態array.I之前分配內存已經對於B

class A //in a.h 

{ 

private: 

    B * b; 

    int maxNumberOfItems; 

    //... 

public: 

A(); 

~A(); 

void addB(const B & something); 

}; 

//in a.cpp 

A::A() 

{ 
    maxNumberOfItems=10; 
    b = new B[maxNumberOfItems]; 

    for(int i=0;i<maxNumberOfItems;i++) 
    { 
    b[i]="";//has to be an empty string, I am getting a segmentation fault 
    } 

} 

A::~A(){/*...*/} 

//... 

//in b.h 

class B 
{ 

private: 

    string name; 

    int price; 

public: 

    void setName(string); 

    string getName(); 

    void setPrice(); 

    int getPrice(int); 

    B & operator=(string &); 

}; 

//in b.cpp 

B & B::operator=(string & a){name = a;price = 0; return *this;} 
+0

循環沒有必要。 'b = new B [maxNumberOfItems]();' – juanchopanza

2
maxNumberOfItems=10; 
//add this line to your code 
b = new B[maxNumberOfItems]; 
//do some error check stuff 
for(int i=0;i<maxNumberOfItems;i++) 
{ 
    b[i]="";//has to be an empty string, I am getting a segmentation fault 
} 

你不爲B [I]分配內存,所以你得到一個段錯誤的程序片段。

+0

謝謝,我完全忘記了分配內存。 – ArcheAngel

+0

@ArcheAngel當你完成它時,不要忘記刪除你分配的內存。 –

+0

不需要循環。 'b = new B [maxNumberOfItems]();' – juanchopanza

3

看起來class A應該是一個動態數組類分配的內存。

當您創建A的新實例時,您還必須爲您的陣列b分配內存。這只是指向內存中某個點的指針。從你發佈的代碼,它不會被初始化,並可以指向任何隨機存儲器的地方 - 這是不好的(即可能是你的段錯誤的原因)。

我建議進行以下更改。

A::A(){ 
    maxNumberOfItems=10; 
    b = new B[maxNumberOfItems]; // b is an array of B objects. 
           // with default constructed values 
    // This way avoids the need for using a for loop and reassigning values 
} 

~A(){ 
    if (b != NULL) { delete b; } 
} 

class B{ 
    private: 
    //.... 
    public: 
    B(): name(""), price(0) {} 
    // Although the default constructor without defining one should behave the same. 
    // This just makes it explicit. what name and price default to. 
}