C++错误:将'char*'赋值给'char [2]的类型不兼容

vic*_*icR 9 c++ error-handling char

我的构造函数有点问题.在我的头文件中,我声明:

char short_name_[2]; 
Run Code Online (Sandbox Code Playgroud)
  • 和其他变量

在我的构造函数中:

Territory(std::string name, char short_name[2], Player* owner, char units);
void setShortName(char* short_name);
inline const char (&getShortName() const)[2] { return short_name_; }
Run Code Online (Sandbox Code Playgroud)

在我的cpp文件中:

Territory::Territory(std::string name, char short_name[2], Player* owner, 
                     char units) : name_(name), short_name_(short_name), 
                    owner_(owner), units_(units)
{ }
Run Code Online (Sandbox Code Playgroud)

我的错误:

Territory.cpp:在构造函数'Territory :: Territory(std :: string,char*,Player*,char)'中:Territory.cpp:15:33:错误:将'char*'赋值给'char [的不兼容类型2]"

我已经想通了,char[2] <=> char*但我不知道如何处理关于我的构造函数和get/setter的问题.

Dav*_*own 15

C++中的原始数组有点烦人,充满了危险.这就是为什么除非你有充分的理由你应该使用std::vectorstd::array.

正如其他人所说的那样,首先,char[2]它与char*通常不同,或者至少不同.char[2]是的大小2阵列charchar*是一个指向char.它们经常会混淆,因为数组会在需要时衰减到指向第一个元素的指针.这样可行:

char foo[2];
char* bar = foo;
Run Code Online (Sandbox Code Playgroud)

但反过来却没有:

const char* bar = "hello";
const char foo[6] = bar; // ERROR
Run Code Online (Sandbox Code Playgroud)

在声明函数参数时,增加混淆char[]等同于char*.所以在你的构造函数中,参数char short_name[2]确实是char* short_name.

数组的另一个怪癖是它们不能像其他类型一样被复制(这是为什么函数参数中的数组被视为指针的原因之一).所以例如我不能做这样的事情:

char foo[2] = {'a', 'b'};
char bar[2] = foo;
Run Code Online (Sandbox Code Playgroud)

相反,我必须迭代foo它们的元素并将它们复制到其中bar,或者使用一些为我这样做的函数,例如std::copy:

char foo[2] = {'a', 'b'};
char bar[2];
// std::begin and std::end are only available in C++11
std::copy(std::begin(foo), std::end(foo), std::begin(bar));
Run Code Online (Sandbox Code Playgroud)

因此,在构造函数中,您必须手动将元素复制short_nameshort_name_:

Territory::Territory(std::string name, char* short_name, Player* owner, 
                     char units) : name_(name), owner_(owner), units_(units)
{ 
    // Note that std::begin and std::end can *not* be used on pointers.
    std::copy(short_name, short_name + 2, std::begin(short_name));
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,这一切都非常烦人,所以除非你有一个很好的理由,你应该使用std::vector而不是原始数组(或者在这种情况下可能std::string).