Problem with const qualifiers to get private atributes of an object
I'm a completely new to C开发者_StackOverflow中文版++ and I'm having a very stupid problem.
I have a Graph class and I need to create a copy constructor for it. This is my class:
#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;
};
There's a function int igraph_copy(igraph_t * to, const igraph_t * from)
in igraph.h
that copies an igraph_t
type adequately.
The constructor and destructor are trivial and work normally, and I have the following copy constructor:
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;
}
When I compile this, I got the following errors:
calsaverini@Ankhesenamun:~/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
I feel this must be something very basic I didn't get about what the const qualifier means.
I don't really know C++ (and I really don't know C that much deeply, for that matter...) but I need to mess with code made by people who do. :(
Any clues or remarks about this copy constructor will be also very humbly appreciated. :P
The getGraph
function needs to be declared with the const
qualifier:
const igraph_t* getGraph() const { ... }
This is because other
is a constant reference. When an object or reference is constant, you can only call member functions of that object which are declared with the const
qualifier. (The const
which appears after the function name and parameter list.)
Note that this also requires you to return a constant pointer.
It's common in C++ to write two "get" functions, one which is constant and the other non-constant, in order to deal with both cases. So you could declare two getGraph() functions:
const igraph_t* getGraph() const { ... }
...and
igraph_t* getGraph() { ... }
The first will be called if the object is constant, and the second will be called if the object is non-constant. You should probably read more about the const member-function qualifier, as well as const-correctness in general.
精彩评论