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