Raf*_*ini 1 c++ constructor const copy-constructor
我是一个全新的C++,我有一个非常愚蠢的问题.
我有一个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;
};
Run Code Online (Sandbox Code Playgroud)
有一个功能int igraph_copy(igraph_t * to, const igraph_t * from),igraph.h可以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;
}
Run Code Online (Sandbox Code Playgroud)
当我编译它时,我得到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
我觉得这必须是非常基本的东西,我没有得到const限定符的含义.
我真的不懂C++(我真的不太了解C,就此而言......)但是我需要搞砸那些做过的人所做的代码.:(
关于这个拷贝构造函数的任何线索或评论也将非常谦虚地赞赏.:P
该getGraph函数需要使用const限定符声明:
const igraph_t* getGraph() const { ... }
这是因为other是一个恒定的参考.当对象或引用是常量时,您只能调用使用const限定符声明的该对象的成员函数.(const出现在函数名称和参数列表之后.)
请注意,这还要求您返回常量指针.
在C++中,编写两个"get"函数是常见的,一个是常量而另一个是非常量,以便处理这两种情况.所以你可以声明两个getGraph()函数:
const igraph_t* getGraph() const { ... }
...和
igraph_t* getGraph() { ... }
如果对象是常量,则调用第一个,如果对象是非常量,则调用第二个.您可能应该阅读有关const成员函数限定符的更多信息,以及一般的const-correctness.
| 归档时间: |
|
| 查看次数: |
696 次 |
| 最近记录: |