C++中的空字符常量

Empty character constant in C++

本文关键字:字符常量 C++      更新时间:2023-10-16

我从一个教程中复制了这段代码。然而,我一直收到一个错误,指出我不能有任何空的字符常量。该教程在Visual Studio 2008中,我使用的是Visual Studio 2013,所以这可能不再有效,但我找不到任何修复程序。

这是代码:

#include "stdafx.h"
#include <iostream>
class MyString
{
    private:
        char *m_pchString;
        int m_nLength;
    public:
        MyString(const char *pchString="")
        {
            // Find the length of the string
            // Plus one character for a terminator
            m_nLength = strlen(pchString) + 1;
            // Allocate a buffer equal to this length
            m_pchString = new char[m_nLength];
            // Copy the parameter into our internal buffer
            strncpy(m_pchString, pchString, m_nLength);
            // Make sure the string is terminated
            // this is where the error occurs
            m_pchString[m_nLength-1] = '';
        }
        ~MyString() // Destructor
        {
            // We need to deallocate our buffer
            delete[] m_pchString;
            // Set m_pchString to null just in case
            m_pchString = 0;
        }
    char* GetString() { return m_pchString; }
    int GetLength() { return m_nLength; }
};
int main()
{
    MyString cMyName("Alex");
    std::cout << "My name is: " << cMyName.GetString() << std::endl;
    return 0;
}

我得到的错误如下:

错误1错误C2137:空字符常量

此行:

m_pchString[m_nLength-1] = '';

你的意思可能是:

m_pchString[m_nLength-1] = '';

甚至:

m_pchString[m_nLength-1] = 0;

字符串以零结尾,写为纯0或空字符''。对于双引号字符串"",零终止字符隐式添加到末尾,但由于显式设置了单个字符,因此必须指定哪个字符。

你说过你"如果我使用null终止符,则得到一个错误,说明strncpy不安全,但您使用strlen,如果字符串不是以null结尾,则就不起作用。来自cplusplus:

C字符串的长度由终止的空字符决定

我的建议是像其他人建议的那样使用null或0,然后每次复制整个字符串时只使用strcpy而不是strncpy

您认为以null结尾的字符串怎么样?是的,你是对的,这样的字符串必须以null结尾:

m_pchString[m_nLength-1] = 0;