2015-12-02 38 views
-3

我正在研究string類型,而我偶然發現了char string[]。它令人困惑,我甚至不知道它是什麼。奇怪的是,在我使用它之後我不能聲明一個string,因爲它使用像一個變量,並且它不允許我聲明其他字符串。那麼如何給這個char數組添加一個名字呢?這裏是代碼,所以我希望可以理解我的意思。謝謝。可以用特定名稱聲明string []嗎?

#include "iostream" 
#include "string.h" 

using namespace std; 


int main(){ 


    char string[] = "hello stackoverflow"; 
    string word("hello stackoverflow"); //cant declare "word" 
    //because i declare it above, and i want to know how to avoid that.. 

    cout<<word; 
    cout<<string; 
} 

我學習的代碼是這樣的:

/* Trim fat from windows*/ 
#define WIN32_LEAN_AND_MEAN 
#pragma comment(linker, "/subsystem:windows") 
/* Pre-processor directives*/ 

#include <windows.h> 
#include "string.h" 
/* Windows Procedure Event Handler*/ 
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM  lParam) 
{ 
    PAINTSTRUCT paintStruct; 
    /* Device Context*/ 
    HDC hDC; 
    /* Text for display*/ 
    char string [] = "hi im a form"; //this is whats i don't understand what  //it is 
    /* Switch message, condition that is met will execute*/ 
    switch(message) 
    { 
     /* Window is being created*/ 
     case WM_CREATE: 
      return 0; 
      break; 
    /* Window is closing*/ 
    case WM_CLOSE: 
     PostQuitMessage('0'); 
     return 0; 
     break; 
    /* Window needs update*/ 
    case WM_PAINT: 
     hDC = BeginPaint(hwnd,&paintStruct); 
     /* Set txt color to blue*/ 
     SetTextColor(hDC, COLORREF(0xffff1a)); 
     /* Display text in middle of window*/ 
     TextOut(hDC,150,150,string,sizeof(string)-1); //and here why its //only able to declare it as "string" and not as a name 
     EndPaint(hwnd, &paintStruct); 
     return 0; 
     break; 
    default: 
     break; 

} 
return (DefWindowProc(hwnd,message,wParam,lParam)); 
} 
+0

簡單:不要說「using namespace std;」'。這會迫使你說'std :: string'。但一般來說,不要給對象與類相同的名稱。基本上不要給同一個名字以上的東西。 – juanchopanza

+0

啊,什麼是名字......很多事情都有C++中的名字:類型,變量,函數......在不同的上下文中,一個名字可能意味着不同的事物。 –

+0

char是一個類型,你的字符串是一個char類型數組的名字。 – g24l

回答

1
char c_str[] = "hello"; 

聲明一個名爲char [6]類型的c_str a.k.a static array of 6 chars"hello"初始化的變量;

std::string cpp_string("hello"); 

聲明一個命名爲"hello"初始化std::stringcpp_string變量。如果添加using namespace std;,則可以使用string而不是std::string

變量的所有聲明必須具有相同的類型。您無法多次定義變量。

您不應該聲明與某個類型具有相同名稱的變量。

相關問題