我应该得到子类的类型,子类应该用我的类型初始化它,但是我可以忘记这样做。
理想情况下,如果没有在派生类的构造函数中初始化此变量,则希望编译器无法编译代码。
我该怎么做?示例代码:
#include <iostream>
enum class AnimalType : int {
kDog = 2, // not null
kCat
};
// Abstract animal
class Animal {
public:
AnimalType GetAnimalType() {
return this->animal_type;
}
// Example virtual method
virtual void Sound() = 0;
protected:
AnimalType animal_type;
};
class Dog : public Animal {
public:
Dog() {
this->animal_type = AnimalType::kDog;
}
void Sound() override {
printf("Woof!\n");
}
};
class Cat : public Animal {
public:
Cat() {
//this->animal_type = AnimalType::kCat;
// I can forget to do it
// How can I make it required?
}
void Sound() override {
printf("Meow!\n");
}
};
int main() {
Animal* dog = new Dog();
Animal* cat = new Cat();
dog->Sound();
cat->Sound();
printf("Dog animal type: %d\n", dog->GetAnimalType());
// undefined behavior, because animal_type is not initialized
printf("Cat animal type: %d\n", cat->GetAnimalType());
delete dog;
delete cat;
system("pause");
return 0;
}输出:屏幕截图
发布于 2020-04-02 07:29:03
为Animal创建合适的构造函数
class Animal {
public:
explicit Animal(AnimalType animal_type) : animal_type(animal_type) {}
virtual ~Animal() = default;
AnimalType GetAnimalType() const { return this->animal_type; }
// Example virtual method
virtual void Sound() = 0;
private:
AnimalType animal_type;
};与用法:
class Dog : public Animal {
public:
Dog() : Animal(AnimalType::kDog) {}
void Sound() override { printf("Woof!\n"); }
};https://stackoverflow.com/questions/60986202
复制相似问题