//基本的向上构造
#include <iostream>
using namespace std;
class A{
public:
void myfunc(){
cout << "A myfunc" << endl;
}
virtual void mytest(){
cout << "A mytest" << endl;
}
};
class B:public A{
public:
void myfunc(){
cout << "B myfunc" << endl;
}
virtual void mytest(){
cout << "B mytest" << endl;
}
};
int main(void){
A* pa = new A();
B* pb = new B();
pa = pb;//向上转型,隐式的,是安全的(pb = static_cast<B*>(pa)是向下转型,不安全的.)
pb->myfunc();//B myfunc
pb->mytest();//B mytest
pa->myfunc();//A myfunc
pa->mytest();//B mytest 向上转型达到,多态的目的.
return 0;
}
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
|
//向上转型+虚函数
#include <iostream>
using
namespace
std;
class
Integer{
public
:
Integer(
int
r):m_r(r){}
virtual
Integer& operator+=(
const
Integer& that){
//虚函数可以为拷贝构造函数.
m_r +=that.m_r;
return
*
this
;
}
int
m_r;
};
class
Complex:
public
Integer{
public
:
Complex(
int
r,
int
i):Integer(r),m_i(i){}
Complex& operator+=(
const
Integer& c){
//这里向上转型,这样
//形参既可以接受Integer也可以接受Complex类型的参数.
Integer::operator+=(c);
m_i += ((
const
Complex&)c).m_i;
//这里是重点,c有可能是const Integer&类型的
//所以强制转换,是可行的.
}
int
m_i;
};
int
main(
void
){
Complex c1(1,2),c2(3,4);
c1 += c2;
cout << c1.m_r <<
'+'
<< c1.m_i <<
'i'
<< endl;
Integer& i1 = c1;
// 4+6i;
Integer& i2 = c2;
//3+4i;
i1+=i2;
//i1调用子类Complex的拷贝赋值函数.
cout << c1.m_r <<
'+'
<< c1.m_i <<
'i'
<< endl;
//7+10i;
return
0;
}
|