2010-10-23 73 views
1

我是一個全新的C++,我有一個非常愚蠢的問題。const修飾符獲得對象的私有屬性的問題

我有一個Graph類,我需要爲它創建一個拷貝構造函數。這是我的課:

#include <igraph.h> 
#include <iostream> 
using namespace std; 


class Graph { 
public: 
    Graph(int N); // contructor 
    ~Graph();  // destructor 
    Graph(const Graph& other); // Copy constructor 
    igraph_t * getGraph(); 
    int getSize(); 

private: 
    igraph_t graph; 
    int size; 
}; 

有在igraph.h是一個函數int igraph_copy(igraph_t * to, const igraph_t * from)那份一個igraph_t型充分。

構造函數和析構函數是微乎其微的,工作正常,我有以下的拷貝構造函數:

Graph :: Graph(const Graph& other) { 
    igraph_t * otherGraph = other.getGraph(); 
    igraph_copy(&graph, otherGraph); 
    size = other.getSize(); 

} 

igraph_t * Graph :: getGraph(){ 
    return &graph; 
} 

int Graph :: getSize() { 
    return size; 
} 

當我編譯此,我得到了以下錯誤:

[email protected]:~/authC/teste$ make 
g++ -I/usr/include/igraph -L/usr/local/lib -ligraph -c foo.cpp -o foo.o 
foo.cpp: In copy constructor ‘Graph::Graph(const Graph&)’: 
foo.cpp:30: error: passing ‘const Graph’ as ‘this’ argument of ‘igraph_t* Graph::getGraph()’ discards qualifiers 
foo.cpp:32: error: passing ‘const Graph’ as ‘this’ argument of ‘int Graph::getSize()’ discards qualifiers 
make: *** [foo.o] Error 1 

我覺得這必須是非常基本的東西,我沒有得到有關const限定符的含義。

我真的不瞭解C++(對於這個問題,我真的不太瞭解C),但是我需要搗亂那些做出來的代碼。 :(

這個拷貝構造函數任何線索或言論也會很虛心地讚賞:P。

回答

5

getGraph功能需要與const預選賽聲明:

const igraph_t* getGraph() const { ... }

這是因爲other是一個常量引用,當一個對象或引用是常量時,只能調用該對象的成員函數,這些成員函數用const限定符聲明(const出現函數名稱和參數列表)

請注意,這也需要您返回一個常量指針。

爲了處理這兩種情況,在C++中編寫兩個「get」函數是常見的,一個是常量,另一個是非常量。所以,你可以聲明瞭兩個getGraph()函數:

const igraph_t* getGraph() const { ... }

...和

igraph_t* getGraph() { ... }

如果對象是恆定的第一個將被調用,第二個將被調用,如果該對象是非常量的。你應該多讀一些關於const member-function qualifier,以及一般const-correctness