预置与弃置函数

预置与弃置函数

在定义函数时尾部带**=delete表示该函数为弃置函数,任何使用弃置函数的地方都为非良构的,即编译器无法编译通过,带=default**表示该函数为预置函数。

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;

class B;

class B{
public:
B();
B(string _str):str(_str){}
~B(){
cout<<"delete B str = "<<str<<endl;
}

private:
string str;
public:
string getStr() const {return str;}
};

class A{
public:
A() = default;
A(string _str):str(_str){}
~A(){
cout<<"delete A str = "<<str<<endl;
}

void test() = delete; //禁止使用

private:
string str;

public:
void printfStr(){
cout<<str<<endl;
}

A& operator= (const A&) = delete; // 禁止使用 = 进行拷贝

A& operator= (const B& b){
this->str = b.getStr();
return *this;
}
};

int main()
{
A *a = new A; //如果A()后面没有 = default则编译报错
delete a;

A a1("a1");
A a2("a2");
//a2.test(); 编译报错 test已弃用

//a1 = a2; 编译报错
B b("b1");
a2 = b;
a2.printfStr();
return 0;
}
#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×