带有"operator="和向量的c ++类,我不知道如何正确使用它

c++ class with 'operator=' and vector, I don't know how to use it correctly

本文关键字:我不知道 何正确 operator 向量 带有      更新时间:2023-10-16

我尝试在特定顶点中的向量(边缘)的特定边缘上使用operator=。 但是我得到了这个错误:

source_file.cpp:在成员函数中 'void Graph::addEdges(int, int, int, int)': source_file.cpp:43:26: 错误: 与 'operator=' 不匹配 (操作数类型为"std::vector"和"Edge")
arr[source].arr2[dest] = Edge(source, dest, a, b);

#include <iostream>
#include <string>
#include <queue>
using namespace std;
const int maxVer = 60;
struct Edge{
int source;
int dest;
int a;
int b;
public:
Edge() : a(0), b(0){};
Edge(int source, int dest, int a, int b) : source(source), dest(dest), a(a), b(b) {}
Edge& operator=(const Edge& e){
source = e.source;
dest = e.dest;
a = e.a;
b = e.b;
return *this;
}
};
struct Vertex{
int parent;
int dest;
bool visited;
int numberEdges;
string str;
vector<Edge> arr2[maxVer-1];
};
class Graph{
int vertexNumber=0;
Vertex arr[maxVer];
queue<int> que;
public:
void addEdges(int source, int dest, int a, int b){
arr[source].arr2[dest] = Edge(source, dest, a, b);
arr[dest].arr2[source] = Edge(dest, source, b, a);
++arr[source].numberEdges;
++arr[dest].numberEdges;
}
};
int main(){
return 0;
}

问题出在哪里?我该如何解决它?

谢谢!

当你这样做时在你的Vertex类中

vector<Edge> arr2[maxVer-1];

您不会声明一个大小为maxVer-1个元素的向量,而是声明一个包含maxVer-1个向量的数组

如果你想要一个向量,那么做:

struct Vertex
{
// Declare the vector
vector<Edge> arr2;
// ... all other member variables...
// Add constructor with a member initializer list
Vertex()
: arr2(maxVer-1)  // Initializes the vector to have maxVer-1 elements
{}
};

请注意更改后的顺序,其中首先声明arr2如果不是,则必须在构造函数成员初始值设定项列表中添加所有其他成员的初始化。

相关文章: