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

时间:2019-04-13 01:41:00

标签: c++ function pointers vector struct

我的编程任务要求我定义一个结构名称为Vector的Student和结构Course的名称为vector的结构,其中包含注册的学生和以下功能:

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

我对正在发生的事情感到困惑,我该如何解决?

1 个答案:

答案 0 :(得分:0)

编译代码时,编译器将在编译struct Course之前开始编译struct Student。因此,在编译Student时,编译器不知道课程是什么。因此,错误,未声明的标识符。要解决此问题,请像下面这样向前声明struct Course:

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


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