2014-11-03 84 views
-5

前幾年考試2中出現以下問題。如何在C++中提供實現?

class SchoolBus 
{ 
public: 
    SchoolBus(int seats, int seatedStudents); 
    bool addStudents(int students); 
    bool removeStudents(int students); 
    int getStudents() const; 

private: 
    int seats; 
    int seatedStudents; 
}; 

2)提供一個SchoolBus構造函數的實現。

SchoolBus(int seats, int seatedStudents) { 
    this->seats = seats; 
    this->seatedStudents = seatedStudents; 
} 

我不明白#2。我明白了這就是答案,但你會如何在代碼中編寫它並編譯它?我想實際編譯它並查看它是如何工作的。

+0

您是否嘗試編譯代碼? – 0x499602D2 2014-11-03 23:33:07

回答

0

構造函數實現沒有正確限定。它應該以類名作爲前綴。

此:

SchoolBus(int seats, int seatedStudents) { 
    this->seats = seats; 
    this->seatedStudents = seatedStudents; 
} 

應該改爲:

SchoolBus::SchoolBus(int seats, int seatedStudents) { 
    this->seats = seats; 
    this->seatedStudents = seatedStudents; 
} 

那麼它應該工作。

0

要麼把它完全符合聲明,如下所示:

class SchoolBus 
{ 
public: 
    SchoolBus(int seats, int seatedStudents) 
    { 
     this->seats = seats; 
     this->seatedStudents = seatedStudents; 
    } 
    bool addStudents(int students); 
    bool removeStudents(int students); 
    int getStudents() const; 

private: 
    int seats; 
    int seatedStudents; 
}; 

或單獨的兩個

//in schoolbus.h 
#pragma once 
class SchoolBus 
{ 
public: 
    SchoolBus(int seats, int seatedStudents); 
    bool addStudents(int students); 
    bool removeStudents(int students); 
    int getStudents() const; 

private: 
    int seats; 
    int seatedStudents; 
}; 

//in schoolbus.cpp 
#include "schoolbus.h" 

SchoolBus::SchoolBus(int seats, int seatedStudents) { 
    this->seats = seats; 
    this->seatedStudents = seatedStudents; 
} 

另外值得一提的是,通常這會在像這樣的初始化列表來完成:

SchoolBus::SchoolBus(int pSeats, int pSeatedStudents) : 
    seats(pSeats), 
    seatedStudents(pSeatedStudents) 
{ 
} 
3

在#2中代碼被稱爲構造函數,所以我會寫的構造而言,我更熟悉:

SchoolBus::SchoolBus(int seating_capacity, int students_in_bus) 
: seats(seating_capacity), 
    seatedStudents(students_in_bus) 
{ 
} 

要編寫它,我可能會放在一個名爲「school_bus.cpp」文件:

#include "school_bus.hpp" 

SchoolBus::SchoolBus(int seating_capacity, int students_in_bus) 
: seats(seating_capacity), 
    seatedStudents(students_in_bus) 
{ 
} 

我會放在一個頭文件中的類聲明,稱 「school_bus.hpp」:

class SchoolBus 
{ 
public: 
    SchoolBus(int seats, int seatedStudents); 
    bool addStudents(int students); 
    bool removeStudents(int students); 
    int getStudents() const; 

private: 
    int seats; 
    int seatedStudents; 
}; 

編譯,我可能會使用g++

g++ -g -o school_bus.o -c school_bus.cpp 

爲了測試它,我想創建一個「main`功能:

#include "school_bus.hpp" 
int main(void) 
{ 
    static SchoolBus yellow_bus(25, 36); 
    return 0; 
} 

這可能需要建設和鏈接:

g++ -g -o school_bus.exe main.cpp school_bus.o 

然後,我可以使用調試器:

gdb ./school_bus.exe