operator用法
总阅读次
operator用法
示例:
- main.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
using namespace std;
MyInt::MyInt(int a, int b)
{
m_a = a;
m_b=b;
}
void MyInt::operator -()
{
m_a = -m_a;
m_b = -m_b;
}
void MyInt::print()
{
cout << "m_a=" << m_a << endl;
cout << "m_b=" << m_b << endl;
}
int main()
{
MyInt F(14, -25);
cout << "取负前:" << endl;
F.print();
-F; //相当于: F.operator-();
cout << "取负后:" << endl;
F.print();
}
- operator_test.h
1
2
3
4
5
6
7
8
9
10
11
12class MyInt
{
private:
int m_a;
int m_b;
public:
MyInt(int a, int b);
void operator - ();
void print();
};
函数重载与定义
- 函数重载示例
mian.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
using namespace std;
Tdate::Tdate()
{
month = 6;
day = 20;
year = 2002;
cout << month << "/" << day << "/" << year << endl;
}
Tdate::Tdate(int m, int d)
{
month = m; day = d; year = 1979;
cout << month << "/" << day << "/" << year << endl;
}
Tdate::Tdate(int m, int d, int y)
{
month = m; day = d; year = y;
cout << month << "/" << day << "/" << year << endl;
}
void main()
{
Tdate adate;
Tdate bdate(7, 2);
Tdate cdate(4, 20, 2006);
}overload.h
1
2
3
4
5
6
7
8
9
10
11class Tdate
{
private:
int month;
int day;
int year;
public:
Tdate();
Tdate(int m, int d);
Tdate(int m, int d, int y);
};
- 函数再定义
- RefinitionFunction.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using namespace std;
class Student
{
public:
void display() { cout << "Student::display()" << endl; }
};
class MiddleStudent :public Student
{
public:
void display() { cout << "MiddleStudent::display()" << endl; }
};
class GraduateStudent :public MiddleStudent
{
public:
void display() {
cout << "GraduateStudent::displayu()" << endl;}
};
- main.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
using namespace std;
void main()
{
Student s;
MiddleStudent ms;
GraduateStudent gs;
s.display();
ms.display();
gs.display();
cout << "------------------------------" << endl;
Student *ps;
ps = &s;
ps->display();
ps = &ms;
ps->display();
ps = &gs;
ps->display();
cout << "------------------------------" << endl;
MiddleStudent *take;
take = &ms;
take->display();
}
【OutPut】
1 | Student::display() |