Git Product home page Git Product logo

Comments (3)

pezy avatar pezy commented on May 22, 2024

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

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

from cppprimer.

xyz4826757 avatar xyz4826757 commented on May 22, 2024

#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的性质造成,但在书中未能找到答案

from cppprimer.

pezy avatar pezy commented on May 22, 2024

{} 在 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"; 就完全可以编译通过,连警告都不会有。

from cppprimer.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.