如何在c ++中提供实现?

时间:2014-11-03 23:26:27

标签: c++ class implementation

  

前几年的考试2中出现了以下问题。

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。我得到的答案是什么,但你会如何在代码中编写并编译它?我想实际编译它,看它是如何工作的。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

构造函数实现未正确限定。它应该以类名为前缀。

:此:

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

应该成为:

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

然后它应该工作。

答案 2 :(得分: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)
{
}