C++中Effective怎么用

这篇文章主要为大家展示了“C++中Effective怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“C++中Effective怎么用”这篇文章吧。

explicit关键字

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

#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;
}

编译成功!

#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;
}

编译失败!

以上是“C++中Effective怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!