gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:39:12 25 4
gpt4 key购买 nike

当我尝试运行这段代码时:

讲师.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;
}

讲师.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;
};

人.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;
};

我收到这些错误:

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();

所有这三个错误都让我感到困惑。如果 Instructor 类派生自 Person,并且在 Person 中 gender 字段受到保护,那么为什么我会收到 error: 'gender' was not declared in this scope,以及 error:不能在没有对象的情况下调用成员函数“virtual void Person::print()”

我觉得我在这里做了一些明显错误的事情,例如错误地包含文件或类似的事情。感谢您的帮助。

最佳答案

您必须在 instructor.h 中包含 person.h,否则标记 Person 对编译器来说是未知的。执行此操作时,请确保从 instructor.cpp 中删除 person.h。否则你将得到重新声明错误。但通常的做法是在头文件中使用 #ifdef 指令来防止多重包含。就像在 person.h

#ifndef PERSON_H
#define PERSON_H


/// class definition and other code


#endif //PERSON_H

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

另一个错误是您没有正确初始化 InstructorPerson 部分。在构造函数中:

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;
}

这样做

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

关于c++: '{' 标记之前的预期类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23507482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com