一、介绍
c++相对c最特别的增加了面向对象的编程,一方面自身可以去设计一些对象,自己使用或者交给他人使用,另一方面官方也提供了很多对象可以直接继承过来自己使用,达到快速开发项目
二、面向对象介绍
面向对象编程,新名词
抽象:本质上和C的结构体类似,相对结构体可以直接在对象里面创建函数
封装:将一个程序功能封装成类,以后直接继承就行,不用重复开发,比如编写一个串口调试助手的类,以后要做新的串口调试助手可以直接继承原来的功能,以前开发的功能需要的直接继承使用,不需要的不使用即可
继承:
多态:
三、编程示例
1、//定义类
class Box{
public://后面的成员可以被外面使用
int len;
int weight;
int height;
int get_v();
void set( int lenghth, int bre, int hei);
private://后面的成员不能被外面使用,默认为此成员,外面访问会报错
int test1;
int set_test1(int x){test1 = x;}
int get_test1(){return test1;}
protected://保护成员,外面访问会报错
int test2;
};
int Box::get_v()
{
int ret = len * weight * height;
return ret;
}
void Box::set( int lenghth, int bre, int hei)
{
len = lenghth;
weight = bre;
height = hei;
}
2、定义对象
Box box1,box2;
3、使用
int v;
box1.set(1,2,3);
v = box1.len * box1.height * box1.weight;
cout << "box1 体积:" << v <<endl;
box2.len = 4;
box2.weight = 5;
box2.height = 6;
v = box2.get_v();
cout << "box2 体积:" << v <<endl;
#include<iostream>
using namespace std;//使用标准输入输出
/*加了直接使用cout作为标准输出,不加这行输出得用std::cout*/
//定义类
class Box{
public://后面的成员可以被外面使用
int len;
int weight;
int height;
int get_v();
void set( int lenghth, int bre, int hei);
private://后面的成员不能被外面使用,默认为此成员,外面访问会报错
int test1;
int set_test1(int x){test1 = x;}
int get_test1(){return test1;}
protected://保护成员,外面访问会报错
int test2;
};
int Box::get_v()
{
int ret = len * weight * height;
return ret;
}
void Box::set( int lenghth, int bre, int hei)
{
len = lenghth;
weight = bre;
height = hei;
}
int main()
{
//定义对象
Box box1,box2;
int v;
box1.set(1,2,3);
v = box1.len * box1.height * box1.weight;
cout << "box1 体积:" << v <<endl;
box2.len = 4;
box2.weight = 5;
box2.height = 6;
v = box2.get_v();
cout << "box2 体积:" << v <<endl;
return 0;
}
编译执行结果
在类里面也可以定义内联函数
四、构造函数
就是在对象初始化的时候,带参数初始化对象,构造函数没有返回值
//定义类
class Human{
public://后面的成员可以被外面使用
Human(int n, int h, int w){num = n; height = h; weight = w;}//构造函数,在创建对象的同时对对象初始化
void print();
private://后面的成员不能被外面使用,默认为此成员,外面访问会报错
int height;
int weight;
int num;
protected://保护成员,外面访问会报错
};
void Human::print()
{
cout << "编号:"<< height << "高:"<< height << "重"<< weight;
}
定义对象,并初始化
Human man1(1, 170, 100);
Human man2(2,180,120);
man1.print();
man2.print();
执行结果
默认构造,
默认系统会创建不带参数的构造函数,自己创建后会屏蔽系统构造的
//定义类
class Human{
public://后面的成员可以被外面使用
Human(){cout << "没有初始化"<< "\n";}//自己创建的默认构造函数
Human(int n, int h, int w){num = n; height = h; weight = w;}//构造函数,在创建对象的同时对对象初始化
void print();
private://后面的成员不能被外面使用,默认为此成员,外面访问会报错
int height;
int weight;
int num;
protected://保护成员,外面访问会报错
};
Human man1(1, 170, 100);
Human man2(2,180,120);
Human man3();
man1.print();
man2.print();
五、析构函数
析构函数作用就是给对象清除后清除对象所占用的内存,析构函数不能带有参数
定义类
class Cow{
public://后面的成员可以被外面使用
Cow(){cout << "默认析构,没有初始化"<< "\n";}//自己创建的默认构造函数
~Cow(){cout << "对象已销毁";}//析构函数,释放内存的时候执行
};
创建对象
Cow my_cow;
执行
六、对象数组
创建对象和结构体一样也支持数组
定义类
class Cow{
public://后面的成员可以被外面使用
Cow(){cout << "默认析构,没有初始化"<< "\n";}//自己创建的默认构造函数
~Cow(){cout << "对象已销毁"<< "\n";}//析构函数,释放内存的时候执行
};
创建对象数组
Cow my_cow;//创建对象
Cow my_cow1[3];//创建对象数组
执行