【问题标题】:error: expected class-name before '{' token ERROR错误:“{”标记之前的预期类名错误
【发布时间】:2012-04-21 22:01:00
【问题描述】:

我的程序中有这个烦人的错误。

“Vehicle”是基类。 “自行车”扩展了这个类。

#ifndef BICYCLE_H
#define BICYCLE_H

#include "Vehicle.h"

#include <string>
#include <iostream>
using namespace std;

//Template class which is derived from Vehicle
template<typename T>
class Bicycle: public Vehicle
{
public:
    Bicycle();
    Bicycle(int, int, string, int); 
    ~Bicycle();

    //Redefined functions inherited from Vehicle
    void move(int, int); // move to the requested x, y location divided by 2
    void set_capacity(int); // set the capacity value; can't be larger than 2

};

上面是 Bicycle.h 文件(我没有这个类的 .cpp 文件)

#ifndef VEHICLE_H
#define VEHICLE_H

#include "PassengerException.h"

#include <string>
#include <iostream>
using namespace std;


//ADD LINE HERE TO MAKE IT A TEMPLATE CLASS
template<typename T>
class Vehicle
{
public:
    Vehicle(); //default contstructor
    Vehicle(int, int, string, int); // set the x, y, name, and capacity
    virtual ~Vehicle(); //destructor; should this be virtual or not???


    //Inheritance - question #1; create these functions here and in Bicycle     class
    string get_name(); // get the name of the vehicle
    void set_name(string); //set the name of the vehicle
    void print(); // std print function (GIVEN TO YOU)

    //Polymorphism - question #2
    virtual void move(int, int); // move to the requested x, y location
    virtual void set_capacity(int); // set the capacity value

    //Operator overloading - question #3
    Vehicle<T> operator+(Vehicle<T> &secondVehicle) const;

    //Exceptions - question #4
    T get_passenger(int) throw(PassengerException); // get the passenger at the specified index
    void add_passenger(T) throw(PassengerException); // add passenger and the current passenger index
    void remove_passenger() throw(PassengerException); // remove a passenger using current passenger index


protected:
    int x_pos;
    int y_pos;
    string name;
    int capacity;
    T *passengers;
    int current_passenger;
};

上面是 Vehicle.h 文件。我也没有 .cpp。

另外,ifndef 定义 endif 是什么意思?我必须使用那些吗?它们是必需的吗?

而且,他们的名字必须这样格式化吗?

【问题讨论】:

  • ifndef endif 只声明你的类一次。你问 (#ifndef) 类是否没有定义,如果不是你定义它。这是标准的事情。

标签: c++


【解决方案1】:
class Bicycle: public Vehicle

Vehicle 是一个模板,所以你需要这个:

class Bicycle: public Vehicle<T>

#ifndef 和 #define 和 #endif 被称为标头保护,用于防止您的头文件被多次包含,从而导致事物(类)被多次声明。

【讨论】:

  • 非常感谢。谢谢解决了我的问题。那么还有一件事,格式化这些守卫的规则是什么?有时我在字符串前面看到_,并且没有“。”像 xxx.h 或 xxx.cpp 中的那些,但是 _.
  • 不要以下划线开头,使用唯一的名称,并保持一致。 #defines 也应该全部大写。我更喜欢将一个名为 Vehicle.h 的文件命名为 VEHICLE_H,因为它在您的帖子中。
【解决方案2】:

ifndef 定义和 endif 是实际基础文件所必需的,即 c++ 文件本身。是的,如果您计划相应地使用这些函数和变量,它们是必需的。是的,他们的名字必须这样格式化,这就是指令或在某些情况下标志必须格式化的方式。

【讨论】:

    【解决方案3】:

    您必须将#endif 放在头文件的末尾。这些被称为定义保护以防止头文件的多次包含。在Include guard 上查看更多信息。

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2015-01-19
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多