C++类和对象
最编程
2024-02-26 09:54:32
...
参考黑马程序员C++
面向对象的三大特性:封装、继承、多态
1 封装
- 将属性和行为作为一个整体,并加以权限控制
- 语法:
class 类名{ 访问权限: 属性 / 行为 };
- 访问权限
- struct默认权限为公有, class默认权限为私有
- private属性可以自己控制读写权限
类别 | 名称 | 类内访问 | 类外访问 | 子类可见 |
---|---|---|---|---|
public | 公共权限 | √ | √ | √ |
protected | 保护权限 | √ | × | √ |
private | 私有权限 | √ | × | × |
//三种权限
//公共权限 public 类内可以访问 类外可以访问
//保护权限 protected 类内可以访问 类外不可以访问
//私有权限 private 类内可以访问 类外不可以访问
class Person
{
//姓名 公共权限
public:
string m_Name;
//汽车 保护权限
protected:
string m_Car;
//银行卡密码 私有权限
private:
int m_Password;
public:
void func()
{
m_Name = "张三";
m_Car = "拖拉机";
m_Password = 123456;
}
};
int main() {
Person p;
p.m_Name = "李四";
//p.m_Car = "奔驰"; //保护权限类外访问不到
//p.m_Password = 123; //私有权限类外访问不到
system("pause");
return 0;
}
2 对象的初始化和清理
2.1 构造函数
- 主要作用于创建对象时为对象的成员属性赋值,自动调用,无需手动调用
-
语法:
类名(){}
- 没有返回值也不用写void
- 函数名 = 类名
- 可以有参数,可以重载
- 自动调用,且只会调用一次
- 当类中有对象成员时,先构造对象成员,再构造本类
2.1.1 有参构造函数 & 无参构造函数(默认构造函数)& 拷贝构造函数
- 默认情况下一般会给一个类四个函数:
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参, 函数体为空)
- 默认拷贝构造函数,对属性进行值拷贝
- 赋值运算符 operator=,对属性进行值拷贝
- 如果用户定义有参构造函数,c++不再提供默认无参构造,但是会提供默认拷贝构造
- 如果用户定义拷贝构造函数,c++不会再提供其他构造函数
- 拷贝构造函数调用时机:
- 使用一个已经创建完毕的对象来初始化一个新对象
- 值传递的方式给函数参数传值
- 以值方式返回局部对象
class Person {
public:
//无参(默认)构造函数
Person() {
cout << "无参构造函数!" << endl;
}
//有参构造函数
Person(int a) {
age = a;
cout << "有参构造函数!" << endl;
}
//拷贝构造函数
Person(const Person& p) {
age = p.age;
cout << "拷贝构造函数!" << endl;
}
//析构函数
~Person() {
cout << "析构函数!" << endl;
}
public:
int age;
};
- 初始化列表方式进行构造
class Person {
public:
//初始化列表方式初始化
Person(int a, int b, int c) :m_A(a), m_B(b), m_C(c) {}
void PrintPerson() {
cout << "mA:" << m_A << endl;
cout << "mB:" << m_B << endl;
cout << "mC:" << m_C << endl;
}
private:
int m_A;
int m_B;
int m_C;
};
int main() {
Person p(1, 2, 3);
p.PrintPerson();
system("pause");
return 0;
}
- 调用构造函数的方法
//调用有参的构造函数
void test02() {
//2.1 括号法,常用
Person p1(10);
//注意1:调用无参构造函数不能加括号,如果加了编译器认为这是一个函数声明
//Person p2();
//2.2 显式法
Person p2 = Person(10);
Person p3 = Person(p2);
//Person(10)单独写就是匿名对象 当前行结束之后,马上析构
//2.3 隐式转换法
Person p4 = 10; // Person p4 = Person(10);
Person p5 = p4; // Person p5 = Person(p4);
//注意2:不能利用 拷贝构造函数 初始化匿名对象 编译器认为是对象声明
//Person p5(p4);
}
注:调用无参构造函数的时候,不能带(), 如果加了,编译器会认为这是一个声明
-
深拷贝 & 浅拷贝:
- 浅拷贝:简单的赋值拷贝操作
- 深拷贝: 在堆区重新申请空间, 进行拷贝操作
如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题
class Person {
public:
//无参(默认)构造函数
Person() {
cout << "无参构造函数!" << endl;
}
//有参构造函数
Person(int age ,int height) {
cout << "有参构造函数!" << endl;
m_age = age;
m_height = new int(height);
}
//拷贝构造函数
Person(const Person& p) {
cout << "拷贝构造函数!" << endl;
//如果不利用深拷贝在堆区创建新内存,会导致浅拷贝带来的重复释放堆区问题
m_age = p.m_age;
m_height = new int(*p.m_height);
}
//析构函数
~Person() {
cout << "析构函数!" << endl;
if (m_height != NULL)
{
delete m_height;
}
}
public:
int m_age;
int* m_height;
};
void test01()
{
Person p1(18, 180);
Person p2(p1);
cout << "p1的年龄: " << p1.m_age << " 身高: " << *p1.m_height << endl;
cout << "p2的年龄: " << p2.m_age << " 身高: " << *p2.m_height << endl;
}
int main() {
test01();
system("pause");
return 0;
}
2.2 析构函数
- 主要作用于对象销毁前系统自动调用,执行一些清理工作
-
语法:
~类名(){}
- 没有返回值也不写void
- 函数名 = 类名, 名称前加上符号~
- 不可以有参数,不可以重载
- 自动调用,且只会调用一次
- 当类中有对象成员时,先析构本类,再析构对象成员
2.3 静态成员(static)
静态成员分为:
- 静态成员变量
- 所有对象共享同一份数据
- 在编译阶段分配内存
- 类内声明,类外初始化
- 静态成员函数
- 所有对象共享同一个函数
- 静态成员函数只能访问静态成员变量
#include<iostream>
using namespace std;
class Person
{
public:
static int m_A; //静态成员变量
//静态成员变量特点:
//1 在编译阶段分配内存
//2 类内声明,类外初始化
//3 所有对象共享同一份数据
static void func()
{
cout << "func调用" << endl;
m_A = 100;
//m_B = 100; //错误,不可以访问非静态成员变量
}
//静态成员函数特点:
//1 程序共享一个函数
//2 静态成员函数只能访问静态成员变量
private:
static int m_B; //静态成员变量也是有访问权限的
//静态成员函数也是有访问权限的
static void func2()
{
cout << "func2调用" << endl;
}
};
int Person::m_A = 10; //类外初始化
int Person::m_B = 10;
int main() {
//静态成员变量两种访问方式
//1、通过对象
Person p1;
p1.m_A = 100;
cout << "p1.m_A = " << p1.m_A << endl;
p1.func();
Person p2;
p2.m_A = 200;
cout << "p1.m_A = " << p1.m_A << endl; //共享同一份数据
cout << "p2.m_A = " << p2.m_A << endl;
//2、通过类名
cout << "m_A = " << Person::m_A << endl;
//2、通过类名
Person::func();
//cout << "m_B = " << Person::m_B << endl; //私有权限访问不到
//Person::func2(); //私有权限访问不到
system("pause");
return 0;
}
类的静态成员变量和函数都不占对象空间,只有非静态成员变量才属于类的对象(占对象空间)
3 this指针
- this指针指向被调用的成员函数所属的对象,不用定义,可以直接使用
- this本质上是指针常量,不可以修改指针的指向
Person* const this;
- 用途:
- 形参与成员变量同名时,用this来区分
- 非静态成员函数返回对象本身,用return *this
- 空指针也可以调用成员函数,但一旦用到this指针,需要增加判空提高代码健壮性
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
//1、当形参和成员变量同名时,可用this指针来区分
this->age = age;
}
Person& PersonAddPerson(Person p)
{
this->age += p.age;
//返回对象本身
return *this;
}
void ShowClassName() {
cout << "我是Person类!" << endl;
}
void ShowPerson() {
if (this == NULL) {
return;
}
cout << age << endl;
}
int age;
};
int main() {
Person p1(10);
cout << "p1.age = " << p1.age << endl;
Person p2(10);
p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p1);
cout << "p2.age = " << p2.age << endl;
Person* p = NULL;
p->ShowClassName(); //空指针,可以调用成员函数
p->ShowPerson(); //但是如果成员函数中用到了this指针,就不可以了
system("pause");
return 0;
}
- 常函数(const)
- 语法:
void 成员函数名() const {}
- 不可以修改成员属性,但当成员属性声明中有关键词mutable,该属性可以在常函数中修改
- 语法:
- 常对象(const)
- 语法:
const 类名 对象名;
- 常对象只能调用常函数
- 语法:
#include<iostream>
using namespace std;
class Person {
public:
Person() {
m_A = 0;
m_B = 0;
}
//this指针的本质是一个指针常量,指针的指向不可修改
//如果想让指针指向的值也不可以修改,需要声明常函数
void ShowPerson() const {
//const Type* const pointer;
//this = NULL; //不能修改指针的指向 Person* const this;
//this->mA = 100; //但是this指针指向的对象的数据是可以修改的
//const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量
this->m_B = 100;
}
void MyFunc() const {
cout << "here" << endl;
//mA = 10000;
}
void noConst() {
cout << "here" << endl;
}
public:
int m_A;
mutable int m_B; //可修改 可变的
};
int main() {
const Person person; //常量对象
Person p;
cout << person.m_A << endl;
//person.mA = 100; //常对象不能修改成员变量的值,但是可以访问
person.m_B = 100; //但是常对象可以修改mutable修饰成员变量
//常对象访问成员函数
person.MyFunc(); //常对象只能调用const的函数
//person.noCount(); 常对象不能调用非const函数
p.noConst();
system("pause");
return 0;
}
4 友元
- 目的:让一些类外的特殊函数或类访问类内私有属性(例如闺蜜可以进卧室)
- 关键字:
friend
- 三种实现:全局函数做友元(goodGay)、类做友元、成员函数做友元
#include<iostream>
using namespace std;
class Building;
class goodLady
{
public:
goodLady();
void visit();
private:
Building* building;
};
class goodBoy
{
public:
goodBoy();
void visit(); //只让visit函数作为Building的好朋友,可以发访问Building中私有内容
void visit2();
private:
Building* building;
};
class Building
{
//告诉编译器 goodGay全局函数 是 Building类的好朋友,可以访问类中的私有内容
friend void goodGay(Building* building);
//告诉编译器 goodLady类是Building类的好朋友,可以访问到Building类中私有内容
friend class goodLady;
//告诉编译器 goodBoy类中的visit成员函数 是Building好朋友,可以访问私有内容
friend void goodBoy::visit();
public:
Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
public:
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
};
void goodGay(Building* building)
{
cout << "好基友正在访问: " << building->m_SittingRoom << endl;
cout << "好基友正在访问: " << building->m_BedRoom << endl;
}
goodLady::goodLady() {
building = new Building();
}
void goodLady::visit()
{
cout << "好基友正在访问" << building->m_SittingRoom << endl;
cout << "好基友正在访问" << building->m_BedRoom << endl;
}
goodBoy::goodBoy() {
building = new Building();
}
void goodBoy::visit()
{
cout << "好基友正在访问" << building->m_SittingRoom << endl;
cout << "好基友正在访问" << building->m_BedRoom << endl;
}
void goodBoy::visit2()
{
cout << "好基友正在访问" << building->m_SittingRoom << endl;
//cout << "好基友正在访问" << building->m_BedRoom << endl;
}
int main() {
Building b;
goodGay(&b);
goodLady gl;
gl.visit();
goodBoy gg;
gg.visit();
system("pause");
return 0;
}
5 运算符重载
- +运算符重载
#include<iostream>
using namespace std;
class Person {
public:
Person() {};
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
//成员函数实现 + 号运算符重载
Person operator+(const Person& p) {
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
public:
int m_A;
int m_B;
};
// 全局函数实现 + 号运算符重载
Person operator+(const Person& p1, const Person& p2) {
Person temp(0, 0);
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
}
// 运算符重载 可以发生函数重载
Person operator+(const Person& p2, int val)
{
Person temp;
temp.m_A = p2.m_A + val;
temp.m_B = p2.m_B + val;
return temp;
}
void test() {
Person p1(10, 10);
Person p2(20, 20);
//成员函数方式
Person p3 = p2 + p1; //相当于 p2.operaor+(p1)
cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;
Person p4 = p3 + 10; //相当于 operator+(p3,10)
cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;
}
int main() {
test();
system("pause");
return 0;
}
- 左移运算符重载(<<)
- 成员函数实现不了,效果是
p << cout
- 可以配合友元来实现输出
- 成员函数实现不了,效果是
class Person {
friend ostream& operator<<(ostream& out, Person& p);
public:
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
//成员函数 实现不了 p << cout 不是我们想要的效果
//void operator<<(Person& p){
//}
private:
int m_A;
int m_B;
};
//全局函数实现左移重载
//ostream对象只能有一个
ostream& operator<<(ostream& out, Person& p) {
out << "a:" << p.m_A << " b:" << p.m_B;
return out;
}
- 递增运算符
class MyInteger {
friend ostream& operator<<(ostream& out, MyInteger myint);
public:
MyInteger() {
m_Num = 0;
}
//前置++
MyInteger& operator++() {
//先++
m_Num++;
//再返回
return *this;
}
//后置++
MyInteger operator++(int) {
//先返回
MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
m_Num++;
return temp;
}
private:
int m_Num;
};
- 赋值运算符重载
class Person
{
public:
Person(int age)
{
//将年龄数据开辟到堆区
m_Age = new int(age);
}
//重载赋值运算符
Person& operator=(Person &p)
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
//编译器提供的代码是浅拷贝
//m_Age = p.m_Age;
//提供深拷贝 解决浅拷贝的问题
m_Age = new int(*p.m_Age);
//返回自身
return *this;
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
//年龄的指针
int *m_Age;
};
- 关系运算符重载
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
};
bool operator==(Person & p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return true;
}
else
{
return false;
}
}
bool operator!=(Person & p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return false;
}
else
{
return true;
}
}
string m_Name;
int m_Age;
};
- 函数调用运算符重载(仿函数)
class MyPrint
{
public:
void operator()(string text)
{
cout << text << endl;
}
};
void test01()
{
//重载的()操作符 也称为仿函数
MyPrint myFunc;
myFunc("hello world");
}
class MyAdd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
void test02()
{
MyAdd add;
int ret = add(10, 10);
cout << "ret = " << ret << endl;
//匿名对象调用
cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}
6 继承
- 继承可以减少重复代码
- 语法:
class 子类(派生类)名字 : 继承方式 父类(基类)名字{}
- 顺序:先父类构造,再子类构造,先子类析构,再父类析构
//公共页面
class BasePage
{
public:
void header()
{
cout << "首页、公开课、登录、注册...(公共头部)" << endl;
}
};
//Java页面
class Java : public BasePage
{
public:
void content()
{
cout << "JAVA学科视频" << endl;
}
};
继承方式 | 基类public | 基类protected | 基类private |
---|---|---|---|
public继承 | public | protected | 不可见 |
protected继承 | protected | protected | 不可见 |
private继承 | private | private | 不可见 |
-
继承同名成员
- 静态成员与非静态成员的处理方式一致,但静态可以通过类名访问
子类中同名成员 | 父类中同名成员 | |
---|---|---|
子类对象 | 直接访问 | 加作用域 |
class Base {
public:
Base()
{
m_A = 100;
}
void func()
{
cout << "Base - func()调用" << endl;
}
void func(int a)
{
cout << "Base - func(int a)调用" << endl;
}
public:
int m_A;
};
class Son : public Base {
public:
Son()
{
m_A = 200;
}
//当子类与父类拥有同名的成员函数,子类会隐藏父类中所有版本的同名成员函数
//如果想访问父类中被隐藏的同名成员函数,需要加父类的作用域
void func()
{
cout << "Son - func()调用" << endl;
}
public:
int m_A;
};
int main() {
Son s;
cout << "Son下的m_A = " << s.m_A << endl;
cout << "Base下的m_A = " << s.Base::m_A << endl;
s.func();
s.Base::func();
s.Base::func(10);
system("pause");
return EXIT_SUCCESS;
}
-
多继承
- 语法:
class 子类 :继承方式 父类1 , 继承方式 父类2... {}
- C++实际开发中不建议使用
- 父类中有同名成员出现,需要增加作用域区分
- 语法:
-
菱形继承
- 两个派生类继承同一个基类,又有某个类同时继承者两个派生类
- 问题:子类继承两份相同的数据,导致资源浪费以及毫无意义
- 解决方案:虚继承
7 多态
-
静态多态
- 复用函数名
- e.g. 函数重载、运算符重载
- 函数地址在编译阶段确定
-
动态多态
- 派生类、虚函数
- 函数地址在运行阶段确定
- 条件
- 有继承关系
- 子类重写父类中的虚函数
- 使用条件
- 父类指针或引用指向子类对象
- 语法:
- 父类定义
virtual 类型 函数名(){}
- 父类定义
class Animal
{
public:
//Speak函数就是虚函数
//函数前面加上virtual关键字,变成虚函数,那么编译器在编译的时候就不能确定函数调用了。
virtual void speak()
{
cout << "动物在说话" << endl;
}
};
class Cat :public Animal
{
public:
void speak()
{
cout << "小猫在说话" << endl;
}
};
class Dog :public Animal
{
public:
void speak()
{
cout << "小狗在说话" << endl;
}
};
void DoSpeak(Animal & animal)
{
animal.speak();
}
int main() {
Cat cat;
DoSpeak(cat);
Dog dog;
DoSpeak(dog);
system("pause");
return 0;
}
-
纯虚函数
- 在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容,因此可以将虚函数改为纯虚函数
- 语法:
virtual 返回值类型 函数名 (参数列表)= 0 ;
-
抽象类
- 定义:类中有纯虚函数
- 无法实例化对象
- 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
- 子类对象使用完后记得销毁
class Base
{
public:
//纯虚函数
//类中只要有一个纯虚函数就称为抽象类
//抽象类无法实例化对象
//子类必须重写父类中的纯虚函数,否则也属于抽象类
virtual void func() = 0;
};
class Son :public Base
{
public:
virtual void func()
{
cout << "func调用" << endl;
};
};
int main() {
Base * base = NULL;
//base = new Base; // 错误,抽象类无法实例化对象
base = new Son;
base->func();
delete base;//记得销毁
system("pause");
return 0;
}
-
虚析构和纯虚析构
- 目的:父类指针释放的时候释放子类对象,如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
- 如果是纯虚析构,该类属于抽象类,无法实例化对象
- 虚析构语法:
virtual ~类名(){}
- 纯虚析构语法:
virtual ~类名() = 0;
类名::~类名(){}
class Animal {
public:
Animal()
{
cout << "Animal 构造函数调用!" << endl;
}
virtual void Speak() = 0;
//析构函数加上virtual关键字,变成虚析构函数
//virtual ~Animal()
//{
// cout << "Animal虚析构函数调用!" << endl;
//}
virtual ~Animal() = 0;
};
Animal::~Animal()
{
cout << "Animal 纯虚析构函数调用!" << endl;
}
//和包含普通纯虚函数的类一样,包含了纯虚析构函数的类也是一个抽象类。不能够被实例化。
class Cat : public Animal {
public:
Cat(string name)
{
cout << "Cat构造函数调用!" << endl;
m_Name = new string(name);
}
virtual void Speak()
{
cout << *m_Name << "小猫在说话!" << endl;
}
~Cat()
{
cout << "Cat析构函数调用!" << endl;
if (this->m_Name != NULL) {
delete m_Name;
m_Name = NULL;
}
}
public:
string *m_Name;
};
int main() {
Animal *animal = new Cat("Tom");
animal->Speak();
//通过父类指针去释放,会导致子类对象可能清理不干净,造成内存泄漏
//怎么解决?给基类增加一个虚析构函数
//虚析构函数就是用来解决通过父类指针释放子类对象
delete animal;
system("pause");
return 0;
}
运行结果:
上一篇: java中的类和对象
下一篇: 什么是类,什么是对象,类和对象的关系
推荐阅读
-
C++ - 列表功能和用法
-
C++STL 开发复习与总结(六): 6. C++ 语言输入/输出流 输入/输出格式的定义 控制-2-1 枚举常量(在 ios 类中)
-
创建一个名为 "人 "的类:属性:姓名、年龄、性别、身高 行为:交谈、添加、更改姓名 编写构造方法,为所有属性赋值; (2) 创建主类:创建一个对象:姓名 "张三",性别 "男",年龄 18,身高 1.80;让该对象调用成员方法:说 "你好!创建一个名为 "张三 "的对象,性别为 "男",年龄为 18 岁,身高为 1.80;让该对象调用成员方法:说 "你好!"计算 23+45 的值。将名称改为 "李四"。
-
二维高斯曲面拟合法的 C++ 实现,用于寻找光斑中心和算法
-
设计模式学习 (IV) - UML 中的类图和类图之间的关系
-
C++:列表类及其模拟实现
-
一起了解 C++ 中的删除和擦除!
-
掌握一篇文章:在 Java 中防止对象溢出和不安全发布
-
学习 C 和 C++ 的 9 条经验
-
60岁拿2000元创业,靠 "神 "做生意,如今年赚24亿--如今的天堂伞集团,无论是口碑还是销量,都是业内首屈一指的 "大牛"。王斌章的一把伞,仅去年的销售额就实现了近6亿元的好成绩。雨伞销售更是占据了中国所有雨伞行业的最大份额。可以说,如今的天堂伞,无论是质量还是口碑,都堪称行业翘楚。 一把天堂伞,如何在王斌章手中打出新高度,玩出大生意?总结起来,两点制胜法宝:一是质量绝对保证,二是服务有保障。这看似很简单,但几十年来不折不扣地执行,特别是在保护伞这个不太重要的对象上,想要做到始终如一,难度很大。这也是为什么中国只有一个王斌章被称为 "全球伞王 "的原因。 天堂伞成立之初,销售场地选在附近的一个广场,以摆摊的形式销售王斌章亲手制作的杭州伞。凭借几十年的手艺和严谨的态度,加上上乘的伞料,即使价格比普通伞高3倍5倍,也打开了市场,积累了第一批人气和资金。