2013-04-20 59 views
2

這是基於GCC/G ++並且通常在Ubuntu上。在C++中聲明字符串爲std:string

這裏是我的示例程序我做:

#include <iostream> 

using namespace std; 

int main() 
{ 

std::string c = "Test"; 
cout << c; 
return 0; 
} 

上面的代碼工作正常。

但我有兩個問題,我不完全得到...

  1. 寫入字符串宣佈爲std:string也能正常工作。有什麼不同。

  2. 如果我用這個std::string類中聲明私有變量,我得到一個錯誤錯誤:「性病」沒有指定類型。這個聲明的例子:

class KType 
{ 
private: 
    std:string N; 

是否有人可以解釋這些問題? 非常感謝!

回答

12

Writing the string declaration as std:string also works fine. What's the difference.

如果您格式化它不同的差別是微小的更加清晰:

std: 
    string c = "Test"; 

你聲明標籤稱爲std,並使用名稱string已被using namespace std;轉儲到全局命名空間中。將它正確地寫爲std::string,您使用std命名空間中的名稱string

If I use this std::string within a class to declare a private variable, I get an error error: ‘std’ does not name a type.

這是因爲您不能在類定義中只在代碼塊中放置標籤。你必須在std::string處正確寫下它。 (如果類是在頭文件中定義,然後using namespace std比源文件更糟糕的想法,所以我勸你不要做那種事。)

另外,如果你使用std::string,那麼你應該#include <string> 。由於<iostream>引入的定義比需要的多,所以看起來你的代碼是偶然發生的,但是你不能輕易依賴它。

+0

這個例子,如果我'格式不同'就是美麗的。謝謝!使很多感覺:) – itsols 2013-04-20 12:53:36

5

您需要包括串類的頭:

#include <string> 

這段代碼有一個錯字,缺第二結腸

std:string N; 

應該是:

std::string N; 

跟單冒號,它會成爲goto的標籤,這可能不是你的意思。

+0

@ Matt-Petersson感謝您的意見。我嘗試過,但它是一樣的。它在第一個例子中工作。所以我不明白爲什麼字符串需要在第二個:( – itsols 2013-04-20 12:39:45

+0

這不是一個錯字,而是我認爲是正確的,因爲它在第一個例子中工作過,但我現在看到, -Seymour'的解釋。謝謝你花時間! – itsols 2013-04-20 13:10:47

2

Writing the string declaration as std:string also works fine. What's the difference.

沒有區別,除非您聲明別的名稱爲string。在您的代碼中,stringstd::string指的是相同的類型。但不惜一切代價避免using namespace std

If I use this std::string within a class to declare a private variable, I get an error error: ‘std’ does not name a type. Example of this declaration:

您需要#include <string>才能使用std::string。發生什麼事情是,在你的第一個代碼示例中,<iostream>似乎包括<string>。你不能依靠那個。您必須包含<string>

+0

對不起,我不小心編輯了這個,而不是我自己的回答。 – 2013-04-20 12:41:00

+0

@MikeSeymour無後顧之憂,我認爲現在全部排序了。 – juanchopanza 2013-04-20 12:43:16

+0

@juanchopanza好的一句:'沒有區別,除非你聲明別的稱爲string'。然後有光:) +1 – itsols 2013-04-20 13:11:49

3

第一個問題:

首先,你缺少的#include <string>指令。您不能依賴其他標題(如<iostream>)到#include標題<string>自動。除了這一點:

問題二:

Writing the string declaration as std:string also works fine. What's the difference.

那是因爲你有一個(惡)在全局命名空間範圍using指令:

using namespace std; 

該指令的效果是,來自std名稱空間的所有名稱都被導入到全局名稱空間中。這就是完全合格std::string和不合格string解析爲相同類型的原因。

如果您省略了using namespace std;指令,則在使用不合格的string名稱時會出現編譯器錯誤。

第三個問題:

If I use this std::string within a class to declare a private variable, I get an error error: ‘std’ does not name a type. Example of this declaration:

你缺少一個冒號。這應該是:

std::string 
//^

而且不

std:string 
//^
+0

你說:'命名空間被導入到全局命名空間'。那麼爲什麼這是不好的?請原諒我的無知;)和很好的解釋+1 – itsols 2013-04-20 13:05:18

+0

@itsols:注意,這個引用與你的摘錄似乎暗示的略有不同;)這是來自'std'命名空間的* names *,它被導入全局命名空間。這種情況不好的原因是,您可能會在*屬於全局名稱空間的名稱和*名稱被導入到全局名稱空間中的名稱之間發生名稱衝突。 – 2013-04-20 13:08:23