2017-02-10 38 views
6

this頁,有五種方式分配的東西轉換爲字符串:我可以分配雙重字符串?

  string (1) string& operator= (const string& str); 
     c-string (2) string& operator= (const char* s); 
     character (3) string& operator= (char c); 
initializer list (4) string& operator= (initializer_list<char> il); 
      move (5) string& operator= (string&& str) noexcept; 

那爲什麼我能編譯下面的文字?編譯器使用了哪個選項?

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string s; 
    double d = 1.0; 
    s = d; 
    std::cout << s << std::endl; 
} 

這是不是隻是一個毫無意義的問題 - 我花了很長時間試圖找到我的代碼這個s = d分配。當然應該是s = std::to_string(d)

編譯器:GCC 4.8.4。

+1

什麼印刷?什麼是's'? –

+0

你真的指的是分配還是你的意思是**轉換成double到string? – Alex

+0

@Alex - 這是分配在我的代碼 – HEKTO

回答

7

您的代碼就相當於這個代碼:

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string s; 
    double d = 1.0; 
    char j = d; 
    s = j; 
    std::cout << s << std::endl; 
} 

所以你會輸出一個\1跟着一行的結局。

如果你使用G ++,指定-Wconversion趕上這樣的事情。

f.cpp:在函數 '詮釋主()':
f.cpp:8:7:警告:轉換從 '雙重' '字符' 可以改變其值[-Wfloat轉換]
s = d;

+0

帶'-Wall'的單個警告?哇。 MSVC/W4說:「警告C4244:從數據的‘雙’到‘字符’,可能損失的轉換:‘參數’」 – rustyx

+0

@RustyX - 是的,我用-Wall編譯 – HEKTO

4

它執行這種轉換:double -> char,因此使用以下過載:

character (3) string& operator= (char c); 

我測試該掃描您的輸出與od

> ./a.out | od -c 
0000000 001 \n