拷贝函数

xiaoxiao2021-02-28  111

拷贝函数

在class中手动写入拷贝构造函数, 以及拷贝赋值函数; 当然也会相应的阻止编译成调用这两个函数;

#include <iostream> #include <cstdlib> #include <string> #include <utility> #include <vector> //聚合类 struct T0 { int x; std::string str; std::vector<int > ve; }; T0 t0 = { 1, "abc" }; //委托构造函数; class T1 { public: T1() : x(0), str(" ") {} T1(int X) : T1() { x = X; } T1(std::string st) : T1(1) { str = st; } private: int x; std::string str; }; //拷贝构造函数; //拷贝构造函数被用来初始化非引用类类型参数, 所以拷贝构造函数加上 (const P &) ; class T2 { public: T2() : x(0), str(" ") {} T2(const T2 &t2) : x(t2.x), str(t2.str) {} //T2(const T2 &t2) {x = t2.x; str = t2.str; } private: int x; std::string str; }; //拷贝赋值函数; //赋值运算符要有一个 operator = (const P &) ; //要求其返回值是左侧运算对象的引用 &operator = ...; class T3 { public: T3() : x(0), str(" ") {} T3 &operator = (const T3 &t3) { x = t3.x; str = t3.str; return *this; } private: int x; std::string str; }; /* T3& T3::operator = (const T3 &t3) { x = t3.x; str = t3.str; return *this; } */ //析构函数; //成员按初始化顺序的逆序依次被销毁; //析构函数本身不直接销毁成员; //但是当一个函数的引用或者指针离开时, 析构函数不会执行; class T4 { public: T4() : x(0), str(" ") {} ~T4() {} private: int x; std::string str; }; //default : 执行默认行为; //构造函数只能有一个 default 默认行为; //只能对合成版本的成员使用 default ; //当default 在函数里面, 为内联, 在外部 default 为外联; class T5 { public: T5() = default; T5(const T5 &) = default; //内联; T5 & operator = (const T5 &); ~T5() = default; private: int x; std::string str; }; T5 & T5::operator = (const T5 &) = default; //外联; //防止执行拷贝; //两种方法阻止拷贝进行 : 1.使用delete, 2.将其放入private中, 不能访问; 一般使用delete; //当拷贝构造函数在时, 一定会有拷贝赋值函数, 反之也是; class T6 { public: T6() = default; T6(const T6 &) = delete; T6 & operator = (const T6 &) = delete; ~T6() = default; private: int x; std::string str; //T6(const T6 &); //T6 & operator = (const T6 &); }; int main() { //无法执行拷贝构造函数, 也就是此函数无法赋值, 拷贝给其他函数; /*T6 t6; T6 t = t6;*/ system("pause"); return 0; }
转载请注明原文地址: https://www.6miu.com/read-18008.html

最新回复(0)