我有一个带有char数组的结构和一个用定义的字符串初始化数组的构造函数。我希望避免使用#define,而是将一个C++字符串传递给构造函数。但话又说回来,char数组的大小在编译时是未知的。什么是解决这个问题的好方法?
#define STRING_ "myString"
struct myStruct {
int nCode;
char str1[sizeof(STRING_)];
myStruct ()
{
nLangCode = 0x0409;
strcpy(str1, STRING_ );
}
} ;发布于 2014-02-10 19:17:23
您应该使用标准类std::string
例如
#include <string>
struct myStruct {
int nLangCode;
std::string str1;
myStruct ( const char *s, int code ) : nLangCode( code ), str1( s )
{
}
} ;否则,您需要使用运算符new动态分配字符数组。在这种情况下,您还必须显式定义复制构造函数、析构函数和复制赋值运算符。
在这种情况下,构造函数可能如下所示
#include <cstring>
struct myStruct {
int nLangCode;
char *str;
myStruct ( const char *s, int code ) : nLangCode( code )
{
str = new char[std::strlen( s ) + 1];
std::strcpy( str, s );
}
// Other special functions...
} ;https://stackoverflow.com/questions/21675560
复制相似问题