- 子类继承父类,父类里的成员可以被子类调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#include <iostream.h>
class
Animal
{
public
:
void
eat()
{
cout<<
"animal eat"
<<endl;
}
void
sleep()
{
cout<<
"animal sleep"
<<endl;
}
};
class
Fish:
public
Animal
{
};
void
main()
{
Animal an;
Fish fh;
fh.sleep();
}
|
2.protected 成员被毕继承只能对在子类内部访问,不能直接访问,父类本身也不能访问。
1
2
3
4
5
6
7
8
9
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
|
#include <iostream.h>
class
Animal
{
public
:
void
eat()
{
cout<<
"animal eat"
<<endl;
}
protected
:
void
sleep()
{
cout<<
"animal sleep"
<<endl;
}
public
:
void
breathe()
{
cout<<
"animal breathe"
<<endl;
}
};
class
Fish:
public
Animal
{
public
:
void
test()
{
sleep();
}
};
void
main()
{
Animal an;
Fish fh;
fh.test();
//子类可以通过内部成员函数来访问父类的保护成员
fh.sleep();
//子类不能直接访问父类的保护成员。
}
|
3. 继承中私有成员无论怎样都不能被子类访问!
4.构造函数。构造子类对象时,先执行父类的构造函数,再执行子类的构造函数。析构的顺序正好与其相反 。
1
2
3
4
5
6
7
8
9
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
|
#include <iostream.h>
class
Animal
{
public
:
Animal(){cout<<
"Animal construction!"
<<endl;}
void
eat()
{
cout<<
"animal eat"
<<endl;
}
protected
:
void
sleep()
{
cout<<
"animal sleep"
<<endl;
}
public
:
void
breathe()
{
cout<<
"animal breathe"
<<endl;
}
};
class
Fish:
public
Animal
{
public
:
Fish(){cout<<
"Fish construction!"
<<endl;}
void
test()
{
sleep();
}
};
void
main()
{
// Animal an;
Fish fh;
fh.test();
//子类可以通过内部成员函数来访问父类的保护成员
// fh.sleep();//子类不能直接访问父类的保护成员。
}
|
1
2
3
4
5
6
7
8
9
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
|
5.子类构造要先构造父类。当父类是有参构造函数,子类构造函数无参时,需要在后面加上 :父类的构造函数
<
div
class
=
"cnblogs_Highlighter"
><pre
class
=
"brush:cpp"
>#include <iostream.h>
class
Animal
{
public
:
Animal(
int
height,
int
weigtht)
//带参数的构造函数
{cout<<
"Animal construction!"
<<endl;}
void
eat()
{
cout<<
"animal eat"
<<endl;
}
protected
:
void
sleep()
{
cout<<
"animal sleep"
<<endl;
}
public
:
void
breathe()
{
cout<<
"animal breathe"
<<endl;
}
};
class
Fish:
public
Animal
{
public
:
Fish():Animal(300,400)
{cout<<
"Fish construction!"
<<endl;}
void
test()
{
sleep();
}
};
void
main()
{
// Animal an;
Fish fh;
fh.test();
//子类可以通过内部成员函数来访问父类的保护成员
// fh.sleep();//子类不能直接访问父类的保护成员。
}
</pre>
</
div
>
|