2012-11-26 57 views
0

我是新來複制構造函數,所以也許我只是不知道他們是如何工作的,但我不明白爲什麼這不起作用。下面是構造函數的實現:爲什麼C++中的這個拷貝構造函數不能編譯?

Heap::Heap(void){ // New empty Heap with default capacity. 
    h_capacity = 10; 
    A = new int[h_capacity]; 
    h_size = 0; 
} 

Heap::Heap(int c){ // New empty Heap with capacity c. 
    A = new int[c]; 
    h_capacity = c; 
    h_size = 0; 
} 

Heap::Heap(int * B, int s, int c){ // New Heap with capacity c containing first s elements of B. 
    A = new int[c]; 
    h_capacity = c; 

    A = new int[h_capacity]; 

    for (int i = 0; i < s; i++){ 
     (A[i]) = B[i]; 
    } 

    h_size = s; 
} 

Heap::Heap(const Heap & H){ // Copy constructor. 
    h_capicity = H->h_capicity; 
    h_size = H->h_size; 

    A = new int[h_capicity]; 

    for (int i = 0; i < h_size; i++){ 
     (A[i]) = H->A[i]; 
    } 

這裏是頭文件:

#include <iostream> 
using namespace std; 

class Heap{ 

public: 
     // Constructors and Destructor 
     Heap(); // New empty Heap with default capacity. 
     Heap(int c); // New empty Heap with capacity c. 
     Heap(int * B, int s, int c); // New Heap with capacity c containing first s elements from B. 
     Heap(const Heap & H); // Copy constructor. 
     ~Heap(); // Destructor. 

     // Size and Capacity 
     bool empty() {return h_size == 0;}; // True iff Heap is empty. 
     int size(){ return h_size ;}; // Current size of Heap. 
     int capacity(){ return h_capacity ;}; // Current capacity. 

     // Operators 
     Heap operator+(const Heap & H) const; // New Heap with combined contents and capacity of operands. 

     // Modifiers 
     void insert(int x); // Insert element x. 
     int extract_min(); // Remove and return the minimum element. 

     // Display 
     void display(); // Print a string representation of the heap contents to standard out. 

private: 
     int* A ; // Array containing heap contents. 
     int h_capacity ; // Max number of elements (= size of A). 
     int h_size ; // Current number of elements. 

     void trickle_up(int i);// Repairs ordering invariant after changing root. 
     void trickle_down(int i);// Repairs ordering invariant after adding a leaf. 
     void make_heap();// Restores ordering invariant to entier contents. 
}; 

但是當我編譯:

heap.cpp: In copy constructor ‘Heap::Heap(const Heap&)’: 
heap.cpp:34: error: ‘h_capicity’ was not declared in this scope 
+0

'h_capicity'的更多的問題是'private'構件。 –

+0

tAmir:複製構造函數可以訪問私有成員。 –

回答

9

你拼錯h_capacityh_capicity

另外,正如其他人指出的那樣,您需要修復->的用法。編譯器會在適當的時候對此抱怨。 :)

P.S.不要忘記定義賦值運算符。

P.P.S.將Heap(int c);標記爲explicit可能是有意義的,以防止從intHeap的不必要的隱式轉換。

+0

+1 cos我很慢:P – Caribou

0

你宣佈

int h_capacity ; // Max number of elements (= size of A). 

和你正在使用

h_capicity = H->h_capicity; 
1
h_capicity = H->h_capicity; 

拼寫錯誤容量

int h_capacity 

,並進一步爲您正在訪問...你便會得到一個錯誤(你是警察的堆對象英作爲指針)它是一個參考,因此它應該是:

h_capacity = H.h_capacity; 

查找使用->代替.

+0

+ 1用於捕捉「治療參考指針」錯誤。 –