C++基类/派生的类用法导致崩溃?

发布于 2025-02-10 18:08:48 字数 1033 浏览 1 评论 0原文

我试图了解继承如何在C ++中起作用。我知道,使用指针时,基类必须使用虚拟灾难,我得到了其背后的原因。

假设我有父母课。

struct Parent {
  Parent() = default;
  virtual ~Parent() = default;

  // And a constructor with specific args
  explicit Parent(std::string name, int age, std::string favoriteColor) : name(std::move(name)), age(age), favoriteColor(std::move(favoriteColor)) {}

  std::string name;
  int age;
  std::string favoriteColor;
  std::string address;
  std::string city;
  std::string state;
};

和儿童课。

struct Child : public Parent {
  using Parent::Parent;
};

// What's the difference between ^^^ version and this:

struct Child : public Parent {
  public:
    explicit Child(std::string name, int age, std::string favoriteColor) : Parent(name, age, favoriteColor) {}
};

我可以创建孩子的实例,但是有时我会在旧的Ubuntu机器上运行此代码崩溃。我如何使用孩子有什么事吗?

std::string name = "johnny";
int age = 37;
std::string color = "red";

Child c{name, age, color}; // This is safe?
Parent &d = c; // Is this safe?

I am trying to understand how inheritance works in C++. I understand that when using pointers, the base class must use a virtual destructor, and I get the reasoning behind it.

Assume I have a parent class.

struct Parent {
  Parent() = default;
  virtual ~Parent() = default;

  // And a constructor with specific args
  explicit Parent(std::string name, int age, std::string favoriteColor) : name(std::move(name)), age(age), favoriteColor(std::move(favoriteColor)) {}

  std::string name;
  int age;
  std::string favoriteColor;
  std::string address;
  std::string city;
  std::string state;
};

And a child class.

struct Child : public Parent {
  using Parent::Parent;
};

// What's the difference between ^^^ version and this:

struct Child : public Parent {
  public:
    explicit Child(std::string name, int age, std::string favoriteColor) : Parent(name, age, favoriteColor) {}
};

I'm able to create instances of Child, but I'm sometimes getting a crash with this code running on an old Ubuntu machine. Is there anything off with how I use the child?

std::string name = "johnny";
int age = 37;
std::string color = "red";

Child c{name, age, color}; // This is safe?
Parent &d = c; // Is this safe?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文