C++ 错误无法为 char g[] 的数组指定显式初始值设定项

C++ error cannot specify explicit initializer for arrays for char g[]

我声明了以下 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 成员以消除此类错误?

我想你可以像下面这样修改你的代码;由于 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;
}
#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) 独角兽应该有角。