我想打印我的 Car 对象的颜色和噪点。我正在尝试在我的 Car 类中使用 c++11 的枚举类。编译时出现错误 Car::Color 和 Car::Noise 不是类、命名空间或范围枚举。我正在使用 :: 运算符来访问枚举类。但错误仍然存在。问题似乎出在 Car.cpp 文件中。这是我的代码。非常感谢任何建议。非常感谢。
汽车.h
class Car {
public:
enum class Color {red, yellow, blue};
enum class Noise {loud, soft, medium};
void setColor();
void setNoise();
void getColor();
void getNoise ();
private:
Color c;
Noise n;
};
汽车.cpp
#include<iostream>
#include "Car.h"
using namespace std;
void Car::setColor() {
c = Color::red;
}
void Car::setNoise() {
n = Noise::loud;
}
void Car::getColor() {
switch(c) {
case Color::red: cout << "red" << endl;
case Color::yellow: cout << "yellow" << endl;
case Color::blue: cout << "blue" << endl;
default:
cout << "error" << endl;
}
}
void Car::getNoise() {
switch(n) {
case Noise::loud: cout << "loud" << endl;
case Noise::soft: cout << "soft" << endl;
case Noise::medium: cout << "medium" << endl;
default: cout << "error" << endl;
}
}
主文件
#include <iostream>
#include "Car.h"
int main() {
Car car;
car.setColor();
car.setNoise();
car.getColor();
car.getNoise();
}