目录
一、拷贝函数
1.调用时机:
(1)使用一个已经创建完毕的对象来初始化一个新对象
(2)值传递的方式给函数参数传值
(3)以值方式返回局部对象
例子:
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person默认构造函数调用"<<endl;
}
Person(int age)
{
cout << "Person有参构造函数调用" << endl;
m_Age = age;
}
Person(const Person& p)
{
cout << "Person拷贝构造函数调用"<<endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "Person析构函数调用"<<endl;
}
int m_Age=0;
private:
};
//1.初始化一个新对象
void test01()
{
Person p1(10);
Person p2(p1);
}
//2.值传递的方式给函数参数传值
void doWork(Person p)
{
}
void test02()
{
Person p;
doWork(p);
}
//3.值方式返回局部对象
Person doWork2()
{
Person p1;
return p1;
}
void test03()
{
Person p = doWork2();
}
int main()
{
//test01();
//test02();
//test03();
system("pause");
return 0;
}
二、深拷贝与浅拷贝
浅拷贝:简单的赋值拷贝工作
深拷贝:在堆区重新申请空间,进行拷贝操作
为了防止在拷贝时,指针类型用new类型赋值时,浅拷贝只有赋值功能,而内存是同样的,使用delete时可能会出现内存重复释放,因此使用深拷贝重新申请空间去储存另外一个对象的数值
例如:
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person默认构造函数调用"<<endl;
}
Person(int age,int height)
{
cout << "Person有参构造函数调用" << endl;
m_Age = age;
m_Height = new int(height);
}
Person(const Person& p)
{
cout << "Person拷贝构造函数调用"<<endl;
m_Age = p.m_Age;
m_Height = new int(*p.m_Height);
}
~Person()
{
if (m_Height != NULL)
{
delete m_Height;
m_Height = NULL;
}
cout << "Person析构函数调用"<<endl;
}
int m_Age=0;
int* m_Height=0;
private:
};
void doWork()
{
Person p1(18, 170);
cout << "p1的年龄身高为:" << p1.m_Age << *p1.m_Height << endl;
Person p2(p1);
cout << "p1的年龄身高为:" << p2.m_Age << *p2.m_Height << endl;
system("pause");
}
int main()
{
doWork();
system("pause");
return 0;
}
三、this指针
this指针指向被调用的函数的成员函数所属的对象
返回值是*this时,返回的是this指向的对象本身
四、友元
友元的三种实现:
1.全局函数做友元
2.类做友元
3.成员函数做友元
设置友元只需要在类的内部使用friend关键字+函数名称/类名称/l类名称::函数名称
有了友元之后,外部的全局函数,类,成员函数就可以访问该类的私有成员
#include<iostream>
#include<string>
using namespace std;
class MyHome
{
//设置友元
friend void goodfriend(MyHome* home);
public:
MyHome()
{
m_sittingroom = "客厅";
m_bedroom = "卧室";
}
string m_sittingroom;
private:
string m_bedroom;
};
void goodfriend(MyHome *home)
{
cout << home->m_sittingroom << endl;
//当goodfriend设置为友元时,可以访问私有成员
cout << home->m_bedroom << endl;
}
void test01()
{
MyHome home01;
goodfriend(&home01);
}
int main()
{
test01();
system("pause");
return 0;
}
五、继承
语法:class 子类:继承方式 父类
继承方式有:
公共继承:public
私有继承:private
保护继承:protect
六、动态多态
派生类和虚函数实现运行时多态
例子:
#include<iostream>
using namespace std;
//动物类
class Animal
{
public:
//虚函数
virtual void speak()
{
cout << "动物在说话" << endl;
}
private:
};
//猫类
class Cat:public Animal
{
public:
void speak()
{
cout << "小猫在说话" << endl;
}
private:
};
void test01()
{
Cat cat;
cat.speak();
}
int main()
{
test01();
system("pause");
return 0;
}
七、STL
1.vector
包含头文件:#include<vector>
(1)内置数据类型
容器:vector
算法:for_each
迭代器:vector<int>::iterator
(2)vector的使用
创建vector数组:vector<数据类型>名称
例如:vector<int>v
插入元素:名称.push_back(元素)
例如:v.push_back(10)
通过迭代器访问容器中的数据:
例如vector<int>::iterator itBegin=v.begin()
例如vector<int>::iterator itEnd=v.end()
v.begin称为起始迭代器指向第一个元素
v.end称为结束迭代器,指向容器中最后一个元素的下一位