首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >构造函数c++中的绑定变量初始化

构造函数c++中的绑定变量初始化
EN

Stack Overflow用户
提问于 2020-04-02 07:22:22
回答 1查看 53关注 0票数 0

我应该得到子类的类型,子类应该用我的类型初始化它,但是我可以忘记这样做。

理想情况下,如果没有在派生类的构造函数中初始化此变量,则希望编译器无法编译代码。

我该怎么做?示例代码:

代码语言:javascript
复制
#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;
}

输出:屏幕截图

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-02 07:29:03

Animal创建合适的构造函数

代码语言:javascript
复制
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;
};

与用法:

代码语言:javascript
复制
class Dog : public Animal {
public:
  Dog() : Animal(AnimalType::kDog) {}

  void Sound() override { printf("Woof!\n"); }
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60986202

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档