2015-01-04 58 views
3
  • 你能解釋一下,爲什麼有差異?
  • 是什麼意思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 
+1

['std :: type_info :: name'](http://en.cppreference.com/w/cpp/types/type_info/name)返回的名稱是編譯器相關的。你不應該把它們用於任何事情。 –

+0

至於你的問題(我認爲)*爲什麼*類型推導的變量不應被推斷爲['std :: initializer_list'](http://en.cppreference.com/w/cpp/utility/initializer_list)?你在初始化中使用'std :: initializer_list'。 –

+2

'C++ filt -t st16initializer_listIPKcE'給出'std :: initializer_list ' – Jarod42

回答

6
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代表指針,K代表const,c代表字符。不知道E可以代表什麼。

+2

好猜測,它們都是正確的。而'''''E'只是標記模板參數列表。 – hvd

+0

@ hvd,很高興知道'我...... E'部分。 –