c ++:'{'标记之前的预期类名

use*_*156 8 c++ netbeans

当我尝试运行此代码时:

Instructor.cpp:

#include "Instructor.h"
#include "Person.h"

using std::string;

Instructor::Instructor() {
    Person();
    salary = 0;
}

Instructor::Instructor(string n, string d, string g, int s) {
    Person(n, d, g);
    salary = s;
}

void Instructor::print() {
    if (gender == "M")
        std::cout << "Mr. ";
    else
        std::cout << "Ms. ";
    Person::print();
    std::cout << "    Instructor, Salary: " << salary << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Instructor.h:

#include <iostream>
#include <string>

class Instructor: public Person 
{
public:
    Instructor();
    Instructor(std::string n, std::string d, std::string g, int s);
    virtual void print();
protected:
    int salary;
};
Run Code Online (Sandbox Code Playgroud)

Person.h:

#include <iostream>
#include <string>

class Person
{
public:
    Person();
    Person(std::string n, std::string d, std::string g);
    virtual void print();
protected:
    std::string name;
    std::string dob;
    std::string gender;
};
Run Code Online (Sandbox Code Playgroud)

我收到这些错误:

In file included from Instructor.cpp:1:0:
Instructor.h:5:1: error: expected class-name before ‘{’ token
 {
 ^
Instructor.cpp: In member function ‘virtual void Instructor::print()’:
Instructor.cpp:16:6: error: ‘gender’ was not declared in this scope
  if (gender == "M")
      ^
Instructor.cpp:20:16: error: cannot call member function ‘virtual void Person::print()’ without object
  Person::print();
Run Code Online (Sandbox Code Playgroud)

所有这三个错误让我感到困惑.如果Instructor类派生自Person,并且Person内的性别字段受到保护,那么为什么我会收到error: ‘gender’ was not declared in this scope,以及error: cannot call member function ‘virtual void Person::print()’ without object

我觉得我在这里做了一些明显错误的事情,例如错误地包含文件或类似的东西.任何帮助表示赞赏.

Rak*_*kib 8

您必须包含person.hin instructor.h,否则Person编译器不知道该令牌.当你这样做,一定要删除person.hinstructor.cpp.否则你将得到重新声明错误.但通常的做法是#ifdef在头文件中使用指令以防止多次包含.像person.h

#ifndef PERSON_H
#define PERSON_H


/// class definition and other code


#endif //PERSON_H
Run Code Online (Sandbox Code Playgroud)

或者你可以#pragma once在VC++中使用 .

另一个错误是你没有正确初始化Person部分Instructor.在构造函数中:

Instructor::Instructor(string n, string d, string g, int s) {
  Person(n, d, g); // this will create a temporary `Person` object instead of initializing base part and 
                   // default constructor of `Person` will be used for this `Instructor` object
  salary = s;
}
Run Code Online (Sandbox Code Playgroud)

像这样做

Instructor::Instructor(string n, string d, string g, int s): Person(n,d,g), salary(s) 
{   }
Run Code Online (Sandbox Code Playgroud)