Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如果我理解正确,则始终在创建派生类的对象时调用基类构造函数。创建派生对象时有没有办法调用重载的基类构造函数?
是的,通过初始化列表:
class Base { public: Base (int n) : mN(n) {} private: int mN; }; class Derived : public Base { public: Derived() : Base (42) {}; // ^^^^^^^^^^^ // Initialization List };
有关初始化列表语法的更多信息,请参阅此问题:
构造函数中这个奇怪的冒号成员(“:”)语法是什么?