我的构造函数有点问题。 在我的头文件中,我声明:
char short_name_[2];
- 和其他变量
在我的构造函数中:
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_; }
在我的cpp文件中:
Territory::Territory(std::string name, char short_name[2], Player* owner,
char units) : name_(name), short_name_(short_name),
owner_(owner), units_(units)
{ }
我的错误:
Territory.cpp: In constructor ‘Territory::Territory(std::string, char*, Player*, char)’: Territory.cpp:15:33: error: incompatible types in assignment of ‘char*’ to ‘char [2]’
我已经想通了 char[2] <=> char*
但我不确定如何处理我的构造函数和 get/setter。
最佳答案
C++ 中的原始数组有点烦人且充满危险。这就是为什么除非你有很好的理由,否则你应该使用 std::vector
或 std::array
。
首先,正如其他人所说,char[2]
与 char*
不同,或者至少通常不同。 char[2]
是大小为 2 的 char
数组,char*
是指向 char
的指针。他们经常感到困惑,因为数组会在需要时衰减到指向第一个元素的指针。所以这有效:
char foo[2];
char* bar = foo;
但反之则不然:
const char* bar = "hello";
const char foo[6] = bar; // ERROR
更令人困惑的是,在声明函数参数时,char[]
等同于char*
。因此在您的构造函数中,参数 char short_name[2]
实际上是 char* short_name
。
数组的另一个怪癖是它们不能像其他类型一样被复制(这是为什么函数参数中的数组被视为指针的一种解释)。例如,我可以不做这样的事情:
char foo[2] = {'a', 'b'};
char bar[2] = foo;
相反,我必须遍历 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));
因此在您的构造函数中,您必须手动将 short_name
的元素复制到 short_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));
}
如你所见,这一切都非常烦人,所以除非你有充分的理由,否则你应该使用 std::vector
而不是原始数组(或者在这种情况下可能是 std::字符串
).
关于C++ 错误 : Incompatible types in assignment of ‘char*’ to ‘char [2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15914220/