阅读579 返回首页    go 阿里云 go 技术社区[云栖]


[面试题]构造函数

(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

  上一篇:go [Python学习] 专题一.函数的基础知识
  下一篇:go Asmack开发系列之XMPP基础