我是 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/