2016-12-15 42 views
1

我知道您不能使用operator+將整數連接到std::string而不將其轉換爲char*std::string爲什麼std :: string在添加整數時返回字符串尾部

但是爲什麼添加一個整數會返回一個字符串的尾部?

#include <iostream> 
#include <string> 
int main() 
{ 
    std::string x; 
    x = "hello world" + 3; 
    std::cout << x << std::endl; 
} 

打印:lo world

如果更改:x = "hello world" + 8;

我們打印:rld

什麼是這背後的原因何在呢?未定義的行爲?

+0

ptr + int = other ptr – Borgleader

+3

'「hello world」'不是'std :: string',它是一個'const char [12]'。 – molbdnilo

+0

你可以少調查一下 - '「hello world」+ 0','「hello world」+ 1','「hello world」+ 2'等等。一種模式很快就會出現。 – molbdnilo

回答

4

末你需要知道你的類型。首先,你是而不是std::string加3。在std::string創建之前會發生添加。相反,您將定義的char[12]加3,因爲char數組衰減到char*,並且向其添加3會使指針前進3個元素。這正是你所看到的。

std::string從結果構造,並且你最終以尾部

0

正如你所知道的字符串是字符數組,如果你把+ 3你,說明你要取字符串從第三位置到它

2

它等同於:

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string x; 
    const char* p = "hello world"; 
    p = p + 3; 
    x = p; 
    std::cout << x << std::endl; 
} 

你可以使它更安全這樣:

#include <iostream> 
#include <string> 

using namespace std::literals; 

int main() 
{ 
    std::string x; 
    x = "hello world"s + 3;  // error! won't compile 
    std::cout << x << std::endl; 
} 
0
int data[5] = { 1, 2, 3, 4, 5 }; 
int *dp = data; 
std::cout << *(dp + 3) << '\n'; 

現在,在這裏,在數據陣列中的4 dp + 3點;這只是指針算術。所以*(dp + 3)是4,這就是你在輸出流中看到的。

具有同樣的事情char*:增加一個整數給你一個新的指針值,由整數的值從原來的偏移:

char data[5] = "abcd"; 
char *dp = data; 
std::cout << *(dp + 3) << '\n'; 

dp點在數組的開始, dp + 3指向字母'd'。所以*(dp + 3)是d,這就是你在輸出中看到的。

你得到同樣的事情,當你使用一個指針和偏移量來初始化std::string類型的對象:該指針加上在字符數組中的位置偏移點,並將得到的std::string對象包含字符的副本從該位置到終止空字符。

相關問題