c++ - 在构造函数c ++中绑定变量初始化
问题描述
我应该得到后代类的类型,后代类应该用我的类型初始化它,但我可以忘记这样做。
理想情况下,如果我没有在派生类的构造函数中初始化这个变量,我想让编译器无法编译代码。
我怎样才能做到这一点?示例代码:
#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;
}
输出:截图
解决方案
为:创建适当的构造函数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"); }
};
推荐阅读
- computer-vision - ArUco 标记代码中的歧义
- xamarin - 如何在 Xamarin 中实现自动登录?
- php - Xpath - 选择具有属性的元素并获取另一个属性值
- java - 如何禁用安全音量警告 SystemUI
- asp.net - 如何在 Asp.Net/VB.Net 中使用 AjaxUploader 上传视频文件时生成缩略图?
- assembly - 如何将数学随机的过程更改为在 dw 中而不是在 db 中返回我?
- c# - Asp.Net Core 2.2 身份认证
- java - 有没有更好的方法处理这种方法中的逻辑条件?
- scala - 将 Spark 数据帧保存到按日期分区的 HDFS
- c# - 无法将值 NULL 插入列错误消息