类的成员函数
类的成员函数是指那些把定义和原型写在类定义内部的函数,就像类定义中的其他变量一样
类成员函数是类的一个成员,它可以操作类的任意对象,可以访问对象中的所有成员
注意:成员可以访问任意的成员(无论时public还是protected,private)
在内部声明并定义
1
2
3
4
5
6
7
8
9
10
|
class Box {
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
double getVolume(void) {
return length * breadth * height;
}
};
|
在内部声明,外部定义
在类的外部使用范围解析运算符 :: 定义该函数
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
|
class complex {
public:
complex();//默认构造函数
complex(double,double);//初始化构造函数
complex(double);//强制转换构造函数
complex operator + (complex);//运算符重载
complex operator - (complex);//运算符重载
friend istream& operator >> (istream& , complex&);//istream类>>运算符重载
friend ostream& operator << (ostream& , complex&);//ostream类<<运算符重载
private:
double real , imag ;
};
//成员函数的类外实现
complex::complex() {
real = 0 ;imag = 0 ;
}
complex::complex(double r , double i ) {
real = r ; imag = i ;
}
complex::complex(double r ) {
real = r ; imag = 0 ;
}
complex complex::operator + (const complex c1) {
complex c2 ;
c2.real = real+c1.real ;
c2.imag = imag+c1.imag ;
return c2 ;
}
complex complex::operator - (const complex c1) {
complex c2 ;
c2.real = real-c1.real ;
c2.imag = imag-c1.imag ;
return c2 ;
}
//友元函数的实现
//实现iostream类的运算符重载
istream& operator >> (istream& input , complex&c ) {
input >> c.real >> c.imag ;
return input ;
}
ostream& operator << (ostream& output , complex&c ) {
output << c.real << '+' << c.imag << 'i' << endl ;
return output ;
}
|
类的友元函数
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员,尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数
友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元
友元函数的定义与声明
如果要声明函数为一个类的友元,需要在类定义中将该函数原型声明,且使用关键字 friend
例子
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Date {
public:
Date(int ,int ,int );//构造函数
friend void Time::display( Date& );//声明Time类中的display函数是Date类的友元成员函数
private:
int month , day , year ;
};
//类外的定义实现
void Time::display(Date &D) {
cout << D.month << '/' << D.day << '/' << D.year << endl ;//引用Date类对象的私有数据
cout << hour << ":" << minute << ":" << second << endl ;
}
|