将基类的实例传递给派生类(Pass instance of base class into derived class)

编程入门 行业动态 更新时间:2024-10-23 14:21:56
将基类的实例传递给派生类(Pass instance of base class into derived class)

在我的应用程序中,我有一个基类类型的对象列表。 每个基类都可以有多个配置(派生类),我一直在试图弄清楚如何将基类传递给派生类,所以我不需要每次都重新初始化值。 我知道我可以通过以下方式实现它,但我很好奇是否有更简单/更少笨重的方式,因为我的代码中的基类需要一段时间来初始化并具有很多功能。

简单示例:

class Base { public: Base(int a, int b) : a(a), b(b) {} protected: int a; int b; }; class Derived : public Base { public: Derived(int c, int d, Base base) : c(c), d(d) { this->a = base.a; this->b = base.b; } private: int c; int d; };

或(由于高开销而试图避免这种情况)

class Base { public: Base(int a, int b) : a(a), b(b) {} protected: int a; int b; }; class Derived : public Base { public: Derived(int c, int d, const Base &base) : Base(base), c(c), d(d) {} private: int c; int d; }

In my application I have a list of objects of my base class type. Each one of the base classes can have multiple configurations (the derived class) and I've been trying to figure out how pass the base class into the derived class so I don't need to reinitialize the values every time. I know I can do it the following ways, but I'm curious if there's an easier/less clunky way since the base class in my code takes a while to initialize and has a lot of features.

Simple Example:

class Base { public: Base(int a, int b) : a(a), b(b) {} protected: int a; int b; }; class Derived : public Base { public: Derived(int c, int d, Base base) : c(c), d(d) { this->a = base.a; this->b = base.b; } private: int c; int d; };

OR (trying to avoid this due to high overhead)

class Base { public: Base(int a, int b) : a(a), b(b) {} protected: int a; int b; }; class Derived : public Base { public: Derived(int c, int d, const Base &base) : Base(base), c(c), d(d) {} private: int c; int d; }

最满意答案

如果Base有一个复制构造函数,那么你可以简单地使用:

class Base { public: Base(int a, int b) : a(a), b(b) {} Base(const Base& base) : a(base.a), b(base.b) {} // make your own or use the default protected: int a; int b; }; class Derived : public Base { public: Derived(int c, int d, const Base& base) : Base(base), c(c), d(d) {} private: int c; int d; }

If Base has a copy constructor then you can simply use:

class Base { public: Base(int a, int b) : a(a), b(b) {} Base(const Base& base) : a(base.a), b(base.b) {} // make your own or use the default protected: int a; int b; }; class Derived : public Base { public: Derived(int c, int d, const Base& base) : Base(base), c(c), d(d) {} private: int c; int d; }

更多推荐

本文发布于:2023-08-07 20:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465600.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   派生类   Pass   将基类   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!