Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于c++ primer 书籍英文版662页,中文版的587页 #49

Closed
xyz4826757 opened this issue Mar 23, 2016 · 3 comments
Closed

关于c++ primer 书籍英文版662页,中文版的587页 #49

xyz4826757 opened this issue Mar 23, 2016 · 3 comments

Comments

@xyz4826757
Copy link

其中有一个Blob articles = {"a","an","the"}//为何不会因为两步隐性类转换发生错误const char*到string以及std::initializer_list到Blob?

include

include

using std::string;

class test{
public:
test(std::initializer_list il) {}
test(string s) {};
};

int main()
{
test t = {"xyz"}; //通过编译
test a = "xyz"; //无法通过编译
return 0;
}
为什么会如此?

@pezy
Copy link
Owner

pezy commented Mar 24, 2016

手头没有纸质书,请告知一下第几章的第几节。

另外, 贴的代码能否保持完整(即贴到编译器可以通过编译那种)?

@xyz4826757
Copy link
Author

#include
#include

using std::string;

class test{
public:
test(std::initializer_list il) { std::cout << "initializer_list" << std::endl; }
test(string s) { std::cout << "string" << std::endl; };
};

int main()
{
test t = {"xyz"}; //通过编译
//test a = "xyz"; //无法通过编译

return 0;

}
本来是完整代码,没想到把头文件不小心漏了,这段代码注释的地方无法编译,这个是由于类隐性转换造成,那么为什么test t = {"xyz"}; 能通过编译,不存在隐性转换呢?我觉得应该是:initializer_list<const char*>才行啊,为什么直接就通过了,在书本的16章1.2节Blob构造函数中的Blob articles = {"a","an","the"},我贴的代码是自己写的测试代码,我怀疑是initializer_list的性质造成,但在书中未能找到答案

@pezy
Copy link
Owner

pezy commented Mar 24, 2016

{} 在 C++ 11 中被重点引入。实际上会构建为一个 initializer_list<T>. 但更重要的是,编译器很照顾它,会为它寻找最恰当的隐式转换。譬如你的代码里,编译器发现 initializer_list<const char[4]> -> initializer_list<std::string> 完全可行。于是就帮你代办了。

更多这样的例子请参考:http://stackoverflow.com/questions/22714859/type-inference-for-stdinitializer-list

注意,只有 {}initializer_list<T> 有这样的待遇。 = 可不一定有。

不过这也取决于 编译器 本身的优化。譬如:在 VS 2013 里,test a = "xyz"; 就完全可以编译通过,连警告都不会有。

@pezy pezy closed this as completed May 6, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants