C++基类/派生的类用法导致崩溃?
我试图了解继承如何在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论