不是类或命名空间错误

时间:2017-03-17 23:44:32

标签: c++ oop

我正在努力解决一个我无法找到解决方案的错误。我似乎无法理解为什么"位置"没有被发现是一个阶级。这是我的头文件:

#ifndef CLASS2_HPP
#define CLASS2_HPP

class Passenger
{

public:

    enum class Location
    {
        Business,
        Economy,
        Vip
    };

    Passenger(Location clas_s, char* firstName, char* secondName, int seat, int terminal, float time_of_departure);

    const char* get_location() const;
    int get_seat() const;
    int get_terminal() const;
    float get_time() const;
    char* get_firstName() const;
    char* get_secondName() const;
    void print() const;

private:

    Location _clas_s;
    char _firstName;
    char _secondName;
    int _seat;
    int _terminal;
    float _time_of_departure;

};


#endif // CLASS2

这是我的cpp文件:

#include <iostream>
#include "Class2.hpp"

using namespace std;


Passenger::Passenger(Location clas_s, char* firstName, char* secondName, int seat, int terminal, float time_of_departure)
: _clas_s(clas_s), _firstName(firstName), _secondName(secondName), _seat(seat), _terminal(terminal), _time_of_departure(time_of_departure) {};

void Passenger::print() const
{
    cout << "Your name is " << _firstName
    << " " << _secondName << endl
    << "Your class is " << get_location() << endl
    << "Your seat is " << _seat << endl
    << "Your terminal is " << _terminal << endl
    << "Your time of departure is " << _time_of_departure << endl;
}

const char* Passenger::get_location() const
{
    switch (_clas_s)
    {
        case Location::Business : return "Business";
        case Location::Economy : return "Economy";
        case Location::Vip : return "Vip";
    }
}

int main() {

    Passenger p((Passenger::Location::Vip), 'John', 'Johnson', 25, 2, 13.53);
    p.print();

    return 0;
}

提前致谢。

3 个答案:

答案 0 :(得分:0)

好像你在使用C ++ 03,所以make

enum Location
{
    Business,
    Economy,
    Vip
};

case Business : return "Business";
case Economy : return "Economy";
case Vip : return "Vip";

编辑:我错了

  

您忘记设置Passenger :: Passenger( Passenger :: 位置   clas_s,...

答案 1 :(得分:0)

创建Passenger时,必须使用双引号传递字符串,而不是单引号(仅适用于单个字符):

Passenger p((Passenger::Location::Vip), "John", "Johnson", 25, 2, 13.53);

然后,您已将_firstName_secondName声明为char。但这只会让你存储一个角色!一个简单的解决方案是使用数组(但使用适当的结构(std::string会更好),因此您不必担心大小):

char _firstName[50];
char _secondName[50];

然后,要初始化它们,你需要#include <cstring>,并且在constrcutor的主体中(不在初始化列表中!)

strcpy(_firstName, firstName);
strcpy(_secondName, secondName);

(同样,std::string会更好,你可以在初始化列表中设置它)

通过这些更改,它可以编译,输出正如预期的那样:

  

你的名字是John Johnson   你的班级是Vip
  你的座位是25
  你的终端是2
  您的出发时间是13.53

ideone上进行了测试。

答案 2 :(得分:0)

您收到此错误:

Class.cpp:24:14: warning: use of enumeration in a nested name specifier is a C++11 extension [-Wc++11-extensions]
        case Location::Business : return "Business";

正如它所述,它是一个C ++ 11特性,所以尝试使用“-std = c ++ 11”选项编译代码。或者使用整数值更改开关案例:

   switch (_clas_s)
    {
        case 0: return "Business";
        case 1: return "Economy";
        case 2: return "Vip";
    }

希望有所帮助。

相关问题