【问题标题】:Why is the default char* in a parameter must be const?为什么参数中的默认char*必须是const?
【发布时间】:2015-04-09 01:54:46
【问题描述】:
class MyString {
private:
    char *m_pchString;
    int m_nLength;
public:
    MyString(char* pchString="0") {      //problem on this parameter
        m_nLength = strlen(pchString)+1;
        m_pchString = new char[m_nLength];
        strncpy(m_pchString, pchString, m_nLength);
        m_pchString[m_nLength-1] = 0;
    }
    ~MyString() {
        delete[] m_pchString;
        m_pchString = 0;
    }
    char* GetString() {return m_pchString;}
    int GetLength() {return m_nLength;}
};

如果我遵守了这个,编译器会给我一个警告:

警告:不推荐将字符串常量转换为 'char*'

除非我将参数从char *pchString = "0"修改为const char *pchString = "0"

为什么参数中的默认char*必须是const?

【问题讨论】:

  • 这与默认参数无关。 C++ 中的字符串文字是const,无论你在哪里使用它们。
  • @Juen Khaw,您可能想将“关于我:”更改为 const char *chStat = "Begineer"; :)
  • @vsoftco,大声笑,你把我搞砸了:P

标签: c++ c++11 visual-c++


【解决方案1】:

因为像"some string" 这样的字符串文字是不可变的,并且尝试修改一个(如果通过非常量引用传递,您可以尝试修改它们)会导致未定义的行为。这就是标准 C++ 不赞成这种转换的原因。

试试这个好玩(但请不要在生产代码中),直播here

#include <iostream>

int main() 
{
    char* str = "test";
    str[0] = 'w';
    std::cout << str; // oops
}

相关:Why are string literals const?

【讨论】:

    【解决方案2】:

    当您使用字符串文字时,例如"0",它被放入程序的只读部分。对此类数据进行任何更改都会导致未定义的行为。通过尝试将char* 类型的变量初始化为字符串字面量,您可以修改只读数据。这就是编译器所抱怨的。

    类似于:

    const int num;
    int* ptr = &num;  // Wrong
    

    【讨论】:

      【解决方案3】:

      原因是与使用字符串类相比,char* 被认为是一种过时的做法。

      【讨论】:

      • 这和string类完全没有关系。
      猜你喜欢
      • 1970-01-01
      • 2012-10-05
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2011-11-25
      • 1970-01-01
      • 2016-11-08
      相关资源
      最近更新 更多