首页 > 解决方案 > 在构造函数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;
}

输出:截图

标签: c++oop

解决方案


为:创建适当的构造函数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"); }
};

推荐阅读