【问题标题】:C++ error cannot specify explicit initializer for arrays for char g[]C++ 错误无法为 char g[] 的数组指定显式初始化程序
【发布时间】:2023-03-21 02:49:01
【问题描述】:

我声明了以下struct

const struct DATABASE_ALREADY_EXISTS {
    const int Code = 2001;
    const char Str[] = "Database already exists.";
};

但是当我将它传递给函数时:

DATABASE_ALREADY_EXISTS DB_ERR;
error_output(DB_ERR.Str, DB_ERR.Code);

它会引发以下错误(Visual Studio 2013):

cannot specify explicit initializer for arrays

这里是声明error_output:

template<class D>
char* error_output(D err_str, int err_code = 0)
{
    return "(" + err_code + ") " + err_str;
}

我应该如何更改struct 的成员Str 的定义以消除此类错误?

【问题讨论】:

    标签: c++ arrays struct char


    【解决方案1】:

    我认为您可以像下面这样修改您的代码;由于 return "(" + err_code + ") " + err_str; 没有任何意义,因此您不能在两个 char * 上应用 + 运算符。

    #include <string>
    #include <iostream>
    #include <cstring>
    #include <sstream>
    
    struct DATABASE_ALREADY_EXISTS {
         DATABASE_ALREADY_EXISTS(const char* s) : Str(s) {}
         static const int Code = 2001;
         const char *Str;
    };
    
    template<class D>
    const char* error_output(D err_str, int err_code = 0)
    {
           std::istringstream is;
           is>>err_code;
    
           std::string str;
           str += "(";
           str += is.str();
           str += ") ";
           str += err_str;
           return str.c_str();
    }
    
    int main(void)
    {
       DATABASE_ALREADY_EXISTS DB_ERR("Database already exists.");
       const char *res = error_output(DB_ERR.Str, DB_ERR.Code);
       std::cout<<res<<std::endl;
        return 0;
    }
    

    【讨论】:

      【解决方案2】:
      #include <iostream>
      using namespace std;
      
      struct Error {
      private:
          static char Buf[1024];
      
      public:
          int Code;
          char* Str;
      
          char* DisplayString() const  {
              sprintf_s(Buf, 1024, "(%d) %s", Code, Str);
              return Buf;
          }
      
          friend ostream& operator<<(ostream& os, const Error& rhs) {
              return os << rhs.DisplayString();
          }
      };
      
      char Error::Buf[1024];
      
      #define DEC_ERROR(name, code, str) Error name = { code, str }
      
      DEC_ERROR(DATABASE_ALREADY_EXISTS, 2001, "Database already exists.");
      DEC_ERROR(UNICORN_WITHOUT_HORN, 2002, "Unicorns should have a horn.");
      
      int _tmain(int argc, _TCHAR* argv[]) {
          cout << DATABASE_ALREADY_EXISTS << endl;
          cout << UNICORN_WITHOUT_HORN << endl;
      }
      

      输出:
      (2001) 数据库已经存在。
      (2002) 独角兽应该有角。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-09
        • 1970-01-01
        • 2019-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多