C++类的特性相关题目

来源:互联网 发布:忘仙商人软件 编辑:程序博客网 时间:2024/06/10 15:57

1.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream> 
using namespace std; 
 
class A 

public
    int _a; 
    A() 
    { 
        _a = 1
    } 
    void print() 
    { 
        printf("%d\n", _a); 
    } 
}; 
 
class B: public A 

public
    int _a; 
    B() 
    { 
        _a = 2
    } 
}; 
 
int main() 

    B b; 
    b.print(); 
    printf("%d\n", b._a); 
    return 0
输出:
1
21 
2 
子类覆盖父类的变量。

2.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22#include <iostream> 
using namespace std; 
 
class base 

private
    int m_i; 
    int m_j; 
public
    base(int i):m_j(i),m_i(m_j){} 
    base():m_j(0),m_i(m_j){} 
    int get_i(){return m_i;} 
    int get_j(){return m_j;} 
}; 
 
int main() 

    base obj(98); 
    cout<<obj.get_i()<<endl 
        <<obj.get_j()<<endl; 
    return 0
输出:
1
2-858993460 
98 

构造函数的初始化变量顺序是按照成员变量的声明顺序来执行的。

3.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32#include <iostream> 
using namespace std; 
 
class B 

private
    int data; 
public
    B() 
    { 
        cout<<"default constructor"<<endl; 
    } 
    ~B() 
    { 
        cout<<"destructed"<<endl; 
    } 
    B(int i):data(i) 
    { 
        cout<<"constructor by parameter"<<data<<endl; 
    } 
}; 
 
B Play(B b) 

    return b; 

 
int main() 

    B temp = Play(5); 
    return 0
输出:
1
2
3constructor by parameter5 
destructed 
destructed 
Play(5)通过隐含类型转换调用B:B(int i),返回时调用析构函数,temp调用拷贝构造函数。

4.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream> 
using namespace std; 
 
class CA 

public
    void f() 
    { 
        cout << "CA f()" << endl; 
    } 
    virtual void ff() 
    { 
        cout << "CA ff()" << endl; 
        f(); 
    } 
}; 
 
class CB : public CA 

public : 
    virtual void f() 
    { 
        cout << "CB f()" << endl; 
    } 
    void ff() 
    { 
        cout << "CB ff()" << endl; 
        f(); 
        CA::ff(); 
    } 
}; 
class CC : public CB 

public
    virtual void f() 
    { 
        cout << "C f()" << endl; 
    } 
}; 
 
int main() 

    CB b; 
    CA *ap = &b; 
    CC c; 
    CB &br = c; 
    CB *bp = &c; 
 
    ap->f(); 
    cout << endl; 
 
    b.f(); 
    cout << endl; 
 
    br.f(); 
    cout << endl; 
 
    bp->f(); 
    cout << endl; 
 
    ap->ff(); 
    cout << endl; 
 
    bp->ff(); 
    cout << endl; 
 
    return 0
输出:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
CA f() 
 
CB f() 
 
C f() 
 
C f() 
 
CB ff() 
CB f() 
CA ff() 
CA f() 
 
CB ff() 
C f() 
CA ff() 
CA f() 
 
指针和引用都能引发多态。



以上题目皆收集自网络、材料等等

0 0
原创粉丝点击