C++复制控制

xiaoxiao2024-04-19  14

当定义一个新类型时,通过使用复制构造函数,赋值操作符,析构函数来显示或隐式地完成对象的复制,赋值,撤销 1.复制构造函数:只有单个形参,而且该形参是对本类类型对象的引用(通常是const修饰)的构造函数,称为~ 复制函数可用于: [color=red] 1)根据另一个同类型的对象显示或隐式初始化一个对象. 2)复制一个对象,将它作为实参传给一个函数 3)从函数返回时复制一个对象 4)初始化顺序容器中的元素 5)根据元素初始化式列表初始化数组元素[/color] a.对象初始化形式 直接初始化:一般是将初始化式放在圆括号内 复制初始化:使用=符号 string str = "123"; //copy-initialization string str1 = str; //copy-initialization b.形参与返回值 当形参或返回值为类类型时,由复制构造函数进行复制 string make_copy(size_t, const string&, const string&); c.初始化容器元素 vector<string> sevc(5); 先用string默认构造函数创建一个临时值为初始化svec,然后使用复制构造函数将临时值复制到sevc的每个元素 2.合成的复制构造函数 执行逐个成员初始化,将新对象初始化原对象的副本 3.定义自己的复制构造函数 MyClass(const MyClass &mc) {//...} 复制构造函数一般不设置为explicit 4.禁止复制 可以将复制构造函数显示的声明为private 5.赋值操作符:对于已初始化过类类型的对象而言,对其赋值时调用赋值操作符函数 MyClass& operator=(const MyClass&) {//... return *this} 6.合成的赋值操作符 逐个成员赋值 一般赋值操作符与复制构造函数一起使用 7.析构函数:撤销类对象,自动调用 三法则:如果类需要析构函数,则其也需要复制构造函数和赋值操作符 ~MyClass() {//...} 8.合成析构函数:按照声明的逆序对非static对象进行撤销,但[color=red][b]不能删除指针成员所指向的对象[/b][/color] 示例: 头文件,rectangle.h /*language:c++author:longsyfile:rectangle.h*/namespace longsy { class Rectangle { int width; int height; public: //带默认实参的默认构造函数 Rectangle(int w=0, int h=0); //复制构造函数 Rectangle(const Rectangle & rect); //赋值操作符 Rectangle& operator=(const Rectangle &rect); //析构造函数 ~Rectangle(); void Draw(); };} 实现文件,rectangle.cpp /*language:c++author:longsyfile:rectangle.cpp*/#include "rectangle.h"using namespace longsy;#include <iostream>Rectangle::Rectangle(int w,int h) : width(w),height(h) { std::cout << "Rectangle(int w,int h)" << std::endl;}Rectangle::Rectangle(const Rectangle &rect) { this->width = rect.width; this->height = rect.height; std::cout << "Rectangle(const Rectangle &rect)" <<std::endl;}Rectangle& Rectangle::operator=(const Rectangle &rect){ this->width = rect.width; this->height = rect.height; std::cout << "operator=(const Rectangle &rect)" << std::endl; return *this;}Rectangle::~Rectangle(){ this->width = 0; this->height = 0; std::cout << "~Rectangle()" << std::endl; }void Rectangle::Draw(){ std::cout << "Draw the rectangle,width:" << this->width \<< ",height:" << height <<std::endl;} 测试文件,test.cpp /*language:c++author:longsyfile:test.cpp*/#include "rectangle.h"using namespace longsy;int main(){ Rectangle rect; //调用默认构造函数 rect.Draw(); Rectangle rect1(1,1); //Rectangle(int w,int h) rect1.Draw(); Rectangle rect2 = rect1;//调用复制构造函数 rect2.Draw(); Rectangle rect3(2,2); //Rectangle(int w,int h) rect3.Draw(); rect3 = rect1; //调用赋值操作符 rect3.Draw(); return (0); //调用析构函数}/*运行结果:Rectangle(int w,int h)Draw the rectangle,width:0,height:0Rectangle(int w,int h)Draw the rectangle,width:1,height:1Rectangle(const Rectangle &rect)Draw the rectangle,width:1,height:1Rectangle(int w,int h)Draw the rectangle,width:2,height:2operator=(const Rectangle &rect)Draw the rectangle,width:1,height:1~Rectangle()~Rectangle()~Rectangle()~Rectangle()*/ 相关资源:C++拷贝文件代码
转载请注明原文地址: https://www.6miu.com/read-5015093.html

最新回复(0)