可以使用特定名称声明字符串[]

It is possible to declare string[] with a specific name?

本文关键字:字符串 声明 定名称 可以使      更新时间:2023-10-16

我正在研究string类型,偶然发现了char string[]。这很令人困惑,我甚至不知道它是什么。奇怪的是,在我使用string之后,我不能声明它,因为它的使用就像一个变量,而且它不允许我声明其他字符串。那么,如何为这个char数组添加一个名称呢?这是代码,所以我希望它能理解我的意思。谢谢

#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));
}
char c_str[] = "hello";

这声明了char [6]类型的名为c_str的变量,也称为用"hello"初始化的static array of 6 chars

std::string cpp_string("hello");

这声明了一个名为cpp_string、类型为std::string、用"hello"初始化的变量。如果添加using namespace std;,则可以使用string而不是std::string

变量的所有声明都必须具有相同的类型。不能多次定义变量。

不应声明与类型同名的变量。