其他分享
首页 > 其他分享> > c – 使用初始化列表分配字符串

c – 使用初始化列表分配字符串

作者:互联网

>你能解释一下,为什么会有差异?
> PKcE是什么意思?

码:

#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
    string s {"IDE"};
    std::cout<<typeid(s).name()<<std::endl;

    auto S{"IDE"};      // why do not deduced as string?
    std::cout<<typeid(S).name()<<std::endl;

    auto c = {"IDE"};  // why do not deduced as string?
    std::cout<<typeid(c).name()<<std::endl;   

    auto C {string{"IDE"}}; // why do not deduced as string?
    std::cout<<typeid(C).name()<<std::endl; 

    auto Z = string{"IDE"};
    std::cout<<typeid(Z).name()<<std::endl; 

}

输出:

Ss
St16initializer_listIPKcE
St16initializer_listIPKcE
St16initializer_listISsE
Ss

解决方法:

string s {"IDE"};  // Type of s is explicit - std::string

auto S{"IDE"};     // Type of S is an initializer list consisting of one char const*.

auto c = {"IDE"};  // Type of c is same as above.

auto C {string{"IDE"}}; // Type of C is an initializer list consisting of one std::string

auto Z = string{"IDE"}; // Type of Z is std::string

我不知道PKcE代表什么.我只能猜测P代表Pointer,K代表const,c代表字符.不知道E可以代表什么.

标签:c,c11,initializer-list
来源: https://codeday.me/bug/20190824/1712212.html