c++ - 无法从 .cpp 访问 .h 文件中的私有(private)成员变量

标签 c++ header-files

我是 C++ 新手,不知道为什么我无法访问返回类型 来自 .h 文件中定义的 .cpp。当我将 Edge::Vertex getVertex1() 更改为 Vertex getVertex1() 时,我只收到错误
错误:使用未声明的标识符“vertex1”(与边类中的顶点 2 相同) 有人可以解释为什么这种方法不好吗?

// Graph.cpp -- Graph contains main function.
#include <iostream>
#include <list>
#include <string>
#include "Vertex.h"
#include "Edge.h"
#define EDGE_DISTANCE 1 
using namespace std;
class Graph
{        
};

int main()
{
   Vertex v1(0);
   Vertex v2(1);
   Edge edge(v1, v2);

   // cout << edge.getVertex1() << endl;
   // cout << edge.getVertex2() << endl;

   return 0;
}
--------------------------------------------------------------
// Edge.h
#ifndef EDGE_H
#define EDGE_H
#include "Vertex.h"
using namespace std;

class Edge
{
    private:
        Vertex vertex1;
        Vertex vertex2;
        int weight;
    public:
       Edge(Vertex,Vertex);
       Vertex getVertex1();
       Vertex getVertex2();
};
#endif
--------------------------------------------------------------
// Edge.cpp
#include "Edge.h"
Edge::Edge(Vertex _vertex1, Vertex _vertex2)
{
   vertex1 = _vertex1;
   vertex2 = _vertex2;
   weight  = 1;
}

Edge::Vertex getVertex1() // error: no type named 'Vertex' in 'Edge'
{
   return vertex1;        // error: use of undeclared identifier 'vertex1'    
}

Edge::Vertex getVertex2()
{
  return vertex2;
}
--------------------------------------------------------------
// Vertex.h
#ifndef VERTEX_H
#define VERTEX_H
#include <list>
using namespace std;

class Vertex
{
  private:
      long id;

  public:
      list<Vertex> adjacentVertexes;
      Vertex();
      Vertex(long);
};
#endif
--------------------------------------------------------------
// Vertex.cpp
#include "Vertex.h"
Vertex::Vertex(long _id)
{
   id = _id;
}

最佳答案

在 Edge.cpp 中,更改以下内容:

Edge::Vertex getVertex1()

至:

Vertex Edge::getVertex1()
Vertex Edge::getVertex2()

您还缺少 Vertex 的空构造函数实现。

关于c++ - 无法从 .cpp 访问 .h 文件中的私有(private)成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49825808/

相关文章:

c++ - 从同一目录读取图像?

c++ - 从函数中按值返回 - 为什么它有效?

c++ - 添加变换后 DirectX 9 不渲染

c++ - 在哪里为 QMainWindow : in header file or in constructor? 声明某些 Qt 对象

无法识别 C++ 标准库头

c++ - 两个不同的 CPP 文件中的相同功能。我该如何做到这一点?

c++ - 体系结构 x86_64 的 undefined symbol :cv::CascadeClassifier::CascadeClassifier()

c++ - PPL - 许可证和链接信息

c++ - 解决 "Theater Row"脑筋急转弯的代码

C++ - 导出 C++ 库公共(public)部分的正确方法