2012-04-21 67 views
0

我的程序中有這個煩人的錯誤。錯誤:在'{'令牌之前預期的類名錯誤

「車輛」是基礎類。 「自行車」擴展了這一類。

#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的含義是什麼?我必須使用這些嗎?他們需要嗎?

而且,他們的名字必須像這樣格式化嗎?

+0

ifndef endif只聲明你的類一次。你問(#ifndef)該類是否沒有定義,以及它是不是你定義它。這是標準的事情。 – Mads 2012-04-21 22:04:30

回答

2
class Bicycle: public Vehicle 

汽車是一個模板,所以你需要這樣的:

class Bicycle: public Vehicle<T> 

的的#ifndef和#定義和#endif被稱爲頭警衛和用於防止頭文件被包含不止一次,導致事物(類)被宣佈不止一次。

+0

非常感謝。謝謝解決了我的問題。還有一件事,那些衛兵的規則是什麼?有時我會在字符串前看到_,並且沒有「。」像xxx.h或xxx.cpp中的那些,而是_。 – FrozenLand 2012-04-21 22:31:50

+0

不要以下劃線開頭,請使用唯一的名稱並保持一致。 #defines也應該全部大寫。我更喜歡名爲say'Vehicle.h'的文件,將它命名爲'VEHICLE_H',因爲它在您的文章中。 – chris 2012-04-21 22:35:43

0

ifndef define和endif是實際基本文件(即C++文件本身)所必需的。如果您打算相應地使用這些功能和變量,那麼需要它們。是的,他們的名字必須以這種方式格式化,這就是指令的格式,或者在某些情況下必須格式化標誌。

0

您必須將#endif放在頭文件的末尾。這些都是所謂的定義警衛,以防止多個包含頭文件。請參閱Include guard

相關問題