服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++ Effective详解

C++ Effective详解

2021-12-24 14:28DUT_LYH C/C++

下面小编就为大家带来一篇C++ Effective的文章。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

 

explicit关键字

用来放置类进行隐式转换
例如一个类有一个形参是int的构造函数
如下,在Pos的vector push的时候 ,直接使用一个int 就可以隐式转换为Pos
如果不想被隐式转换 就加上explicit关键字

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
#include <list>
using namespace std;
#define debug(x) cout<<#x<<": "<<(x)<<endl;
class Pos {
public:
    Pos() {
    }
    Pos(int x) {
    }
};
int main(int argc, const char* argv[]) {
    vector<Pos> arr;
    //arr.reserve(1e5);
    for (int i = 0; i < 1e5; ++i) {
        arr.push_back(1);
    }
    return 0;
}

编译成功!

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
#include <list>
using namespace std;
#define debug(x) cout<<#x<<": "<<(x)<<endl;
class Pos {
public:
    explicit Pos() {
    }
    explicit Pos(int x) {
    }
};
int main(int argc, const char* argv[]) {
    vector<Pos> arr;
    //arr.reserve(1e5);
    for (int i = 0; i < 1e5; ++i) {
        arr.push_back(1);
    }
    return 0;
}

编译失败!

 

总结

本片文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/L1558198727/article/details/119974918

延伸 · 阅读

精彩推荐