代码之家  ›  专栏  ›  技术社区  ›  Rafael S. Calsaverini

获取对象私有属性的常量限定符的问题

  •  1
  • Rafael S. Calsaverini  · 技术社区  · 14 年前

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

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

    当我编译这个时,我得到了以下错误:

    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页

    1 回复  |  直到 14 年前
        1
  •  5
  •   Charles Salvia    14 年前

    这个 getGraph 函数需要用 const 限定符:

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

    这是因为 other 是一个常量引用。当对象或引用是常量时,只能调用该对象的成员函数 常量 常量 出现的 之后

    注意,这还需要返回一个常量指针。

    在C++中,通常写两个“获取”函数,一个是常数,另一个是非常数,以处理这两种情况。所以可以声明两个getGraph()函数:

    const iggraph_t*getGraph()常量{。。。}

    igraph_t* getGraph() { ... }

    如果对象是常量,则调用第一个;如果对象是非常量,则调用第二个。你应该多看看 const member-function qualifier ,以及 const-correctness