第4章 类与对象
1.抽象、封装
抽象:对同一类对象的共同属性和行为进行概括,形成类。

封装:将抽象出的数据、代码封装在一起,形成类。

2.类和对象的关系

3.类定义的语法形式
class 类名称
{
public:
公有成员(外部接口)
private:
私有成员
protected:
保护型成员
}
4.类成员
- 私有类型成员

- 公有类型成员

- 保护类型成员
5.对象定义的语法
类名 对象名;
例:Clock myClock;
类中成员互相访问时直接使用成员名访问
类外访问使用“对象名.成员名”方式访问public属性的成员
6.类的定义(钟表类)
#include <iostream>
using namespace std;
class Clock {
public:
void setTime(int newH = 0, int newM = 0, int newS = 0);
void showTime();
private:
int hour, minute, second;
};
7.对象的使用
int main() {
Clock myclock;
myclock.setTime(8, 30, 30);
myClock.hsowTime();
return 0;
}
8.类的成员函数

内联成员函数

9.构造函数(对对象进行初始化,在对象创建时被自动调用)
例:Clock myclock(0,0,0);
形式:

隐含生成的构造函数:

默认构造函数:

#include <iostream>
using namespace std;
class Clock {
public:
Clock(int newH, int newM, int newS);//构造函数
void setTime(int newH = 0, int newM = 0, int newS = 0);
void showTime();
private:
int hour, minute, second;
};
10.委托构造函数(为了避免代码重复)
Clock类的两个构造函数:

11.复制构造函数

定义:


构造函数被调用的三种情况:

例:Point 类
class Point {
public:
Point(int xx = 0, intyy = 0) { x = xx; y = yy; }
Point(const Point&p)
void setX(intxx) { x = xx; }
void setY(intyy) { y = yy; }
int getX()const { return x; }//常函数
int getY()const { return Y; }//常函数
private:
int x, y;
};
复制构造函数的实现:
Point::Point(const Point& p) {
x = p.x;
y = p.y;
cout << "Calling the copy constructor" << endl;
}
12.右值引用

13.移动构造函数

14.析构函数

15.类的组合
概念:

构造函数设计:

构造组合类对象时的初始化次序

例题:线段类
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
Point(int xx = 0, intyy = 0) {
x = xx;
y = yy;
}
Point(Point &p)
int getx() { return x; }
int getY() { return y; }
private:
int x, y;
};
class Line {
public:
Line(Point xp1, Point xp2);
Line(Line& l);
double getLen() { return len; }
private:
Point p1, p2;
double len;
};
Line::Line(Point xp1, Point xp2) :p1(xp1), p2(xp2) {
cout << "Calling constructor of Line" << endl;
double x = static_cast<double>(p1.getX() - p2.getX());
double y = static_cast<double>(p1.getY() - p2.getY());
len = sqrt(x * x + y * y);
}
Line::Line(Line& l) :p1(l.p1), p2(l.p2) {
cout << "Calling the copy constructor of Line" << endl;
len = l.len;
}
16.前向引用声明:
注意事项:

浙公网安备 33010602011771号