-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo20.cpp
104 lines (92 loc) · 1.89 KB
/
demo20.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <iostream>
using namespace std;
class Calculator
{
public:
int getResult(string oper)
{
if(oper == "+")
{
return m_Num1 + m_Num2;
}
else if(oper == "-")
{
return m_Num1 - m_Num2;
}
else if(oper == "*")
{
return m_Num1 * m_Num2;
}
}
int m_Num1;
int m_Num2;
};
void test01()
{
Calculator c;
c.m_Num1 = 10;
c.m_Num2 = 5;
cout << c.m_Num1 << " + " << c.m_Num2 << " = " << c.getResult("+") << endl;
cout << c.m_Num1 << " - " << c.m_Num2 << " = " << c.getResult("-") << endl;
cout << c.m_Num1 << " * " << c.m_Num2 << " = " << c.getResult("*") << endl;
}
class AbstactCalculator
{
public:
virtual int getResult()
{
return 0;
}
int m_Num1;
int m_Num2;
};
class AddCalculator : public AbstactCalculator
{
public:
int getResult()
{
return m_Num1 + m_Num2;
}
};
class Subculator : public AbstactCalculator
{
public:
int getResult()
{
return m_Num1 - m_Num2;
}
};
class MulCalculator : public AbstactCalculator
{
public:
int getResult()
{
return m_Num1 * m_Num2;
}
};
void test02()
{
//多态的使用条件
//父类指针或者引用指向子类对象
//加法运算
AbstactCalculator *abc = new AddCalculator;
abc->m_Num1 = 10;
abc->m_Num2 = 10;
cout << abc->m_Num1 << "+" << abc->m_Num2 << " = " << abc->getResult() << endl;
delete abc;
abc = new Subculator;
abc->m_Num1 = 10;
abc->m_Num2 = 10;
cout << abc->m_Num1 << "-" << abc->m_Num2 << " = " << abc->getResult() << endl;
delete abc;
abc = new MulCalculator;
abc->m_Num1 = 10;
abc->m_Num2 = 10;
cout << abc->m_Num1 << "*" << abc->m_Num2 << " = " << abc->getResult() << endl;
}
int main()
{
test02();
system("pause");
return 0;
}