在#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
您是否嘗試編譯代碼? – 0x499602D2 2014-11-03 23:33:07