enum class EmployeeType {Employee, Manager, Sales, Unknown};
class Employee
{
public:
Employee() = delete;
Employee(const Employee&) = delete;
Employee& operator=(const Employee&) = delete;
Employee& operator=(Employee&&) = delete;
Employee(Employee&&) = default;
explicit Employee(EmployeeType type);
}
当我在main()中写道时:
Employee e1(EmployeeType::Manager);
或
Employee e2(Employee(EmployeeType::Manager));
它工作正常。 当我这样写:
Employee e3({});
Employee e4(EmployeeType{});
Employee e5(EmployeeType(123));
编译器编译它。但我想禁止使用c ++关键字或使用其他东西。我不知道怎么做。 我只允许这样:
Employee e6(EmployeeType::Employee);
Employee e7(EmployeeType::Manager);
Employee e8(EmployeeType::Sales);
Employee e9(EmployeeType::Unknown);
Employee e10(Employee(EmployeeType::Employee));
Employee e11(Employee(EmployeeType::Manager));
Employee e12(Employee(EmployeeType::Sales));
Employee e13(Employee(EmployeeType::Unknown));
我该怎么做?
我在Ubuntu 16.04 LTS中使用g ++ 5.4.0。
我在Qt Creator 4.1.0中编写了代码,并在pro-file中启用了C ++ 11:
CONFIG += c++11
答案 0 :(得分:4)
您可以通过声明Employee e3({});
构造函数来阻止initializer_list
。当初始化程序是支撑列表时,这始终是首选:
Employee(std::initializer_list<int>) = delete;
模板类型并不重要。
但是,无法阻止调用者向EmployeeType
转换某些值,然后将其作为构造函数参数提供。