2010-10-23 71 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