C++的explicit的作用与隐式转化

前端之家收集整理的这篇文章主要介绍了C++的explicit的作用与隐式转化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

了解explicit之前,要先弄清楚什么是隐式转化。隐式转化既是当构造器只有一个参数时或有多个默认参数时,可以直接用 “ = ”直接赋值。如下:

#include "pch.h"

#include

#include

#include "malloc.h"

using namespace std;

class A

{

public:

A(int a = 5) { this->a = a; };

int getA() { return a; };

private:

int a;

};

int main()

{

A s;

s = 20; //可以直接对s的唯一参数进行修改

cout << "s.a = " << s.getA() << endl;

return EXIT_SUCCESS;

}

但是当多个参数的构造器时,这样的隐式转化只会对第一个进行修改,这就出现了一些歧义。

#include "pch.h"

#include

#include

#include "malloc.h"

using namespace std;

class A

{

public:

A(char c = 'a',int a = 5): c(c),a(a) {};

int getA() { return a; };

char getC() { return c; };

private:

char c;

int a;

};

int main()

{

A s;

s = 'd';

s = 120;//就是ASCII码的 x

cout << "s.c = " << s.getC() << endl;

cout << "s.a = " << s.getA() << endl;

return EXIT_SUCCESS;

}

结果就只有c变为x。

所以用explicit修饰构造器,编译器就会避免这种隐式转化。

猜你在找的C#相关文章