编译错误:2 个重载没有'this'指针的合法转换。使用结构

Compile Error: 2 overloads have no legal conversion for 'this' pointer. Working with structs

本文关键字:转换 结构 指针 this 重载 编译 错误      更新时间:2023-10-16

我的编程作业要我定义一个具有名称向量的结构 Student 和一个具有名称和包含已注册学生和以下函数的向量的结构 Program:

void print_student(Student* s)
void print_course(Course* c)
void enroll(Student* s, Course* c)
//enrolls given student in the given course and updates both vectors

我尝试在注册函数参数中添加与号来修复它,但它不起作用。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Student 
{
string Name ;
vector < Course* > Courses;
};
struct Course 
{
string Name ;
vector < Student* > Students;
};
void print_Student(Student* s)
{
cout << s->Name << endl;
for (int i = 0; i < s->Courses.size(); i++)
{
cout << s->Courses[i] << endl;
}
};
void print_course(Course* c)
{
cout << c->Name << endl;
for (int i = 0; i < c->Students.size(); i++)
{
cout << c->Students[i] << endl;
}
};
void enroll(Student* &s, Course* &c)
{
cout << "Enrolled " << s << "in " << c << endl;
s->Courses.push_back( c ); 
c->Students.push_back( s);
}

int main()
{
Student* Bob;
Course* ComputerScience;
Bob->Name = "Bob";
ComputerScience->Name = "Computer Science";
enroll( Bob , ComputerScience);
system("Pause");
}

我希望代码能够让学生 Bob 注册到计算机科学课程,以便我以后可以定义更多学生并打印他们。

代码看起来不错,但是在运行编译器时给我以下错误:

source.cpp(10): error C2065: 'Course': undeclared identifier
source.cpp(10): error C2059: syntax error: '>'
source.cpp(10): error C2976: 'std::vector': too few template arguments
source.cpp(41): error C2663: 'std::vector<_Ty,_Alloc>::push_back': 2 overloads have no legal conversion for 'this' pointer

我对发生了什么感到困惑,我该如何解决它?

编译代码时,编译器在编译结构 Course 之前开始编译结构 Student 。因此,在编译学生时,编译器不知道课程是什么。因此错误,未声明的标识符。要修复它,请像这样向前声明结构 Course:

struct Course;
struct Student 
{
string Name ;
vector < Course* > Courses;
};

struct Course 
{
string Name ;
vector < Student* > Students;
};