[麵試題]構造函數
(1)class Person{ Person(int age){ } }; class Student:Person{ }; int main(){ Student student; }
A、Compile-time error at 5.
B、Compile-time error at 1.
C、The compiler attempts to create a default constructor for class B.
D、The compiler attempts to create a default constructor for class A.
解析:A
報錯:error: no matching function for call to 'Person::Person()“
原因是因為子類Student中沒有定義構造方法,那麼就會有一個默認的無參構造方法,我們知道,在創建子類對象的時候,會調用父類的構造方法無參構造方法,因為Person類定義了一個帶參數的構造方法,所以無參構造方法被覆蓋了,所以在第5行會報A類中沒有無參構造方法。
隻要給Person定義一個無參構造方法就行了。
class Person{ Person(int age){ }; public: Person(){ }; }; class Student:Person{ };
(2)構造函數的初始化列表
class Person{ private: int b; const int c; int &d; public: Person(int a); }; Person::Person(int a){ b = a; c = a; d = a; }報錯:
error: uninitialized member 'Person::c' with 'const' type 'const int'
error: uninitialized reference member 'Person::d'
error: assignment of read-only data-member 'Person::c'
解析:可以初始化const對象或引用類型對象,但不能對他們進行賦值。在開始執行構造函數的函數體之前,要完成初始化。初始化const對象或引用類型對象
唯一的一個機會是在構造函數初始化列表中。
正確方式:
Person::Person(int a):b(a),c(a),d(a){ }
最後更新:2017-04-03 05:40:17