gpt4 book ai didi

c++ - 使用 const 限定符获取对象私有(private)属性的问题

转载 作者:行者123 更新时间:2023-11-30 01:30:53 27 4
gpt4 key购买 nike

我是 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;
};

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;
}

编译时出现如下错误:

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

我觉得这一定是一些非常基本的东西,我不明白 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 member-function qualifier 的更多信息,以及 const-correctness一般而言。

关于c++ - 使用 const 限定符获取对象私有(private)属性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4006553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com