2013-04-09 375 views
7

我的构造函数有点问题。 在我的头文件我宣布:C++错误:将'char *'赋值给'char [2]的不兼容类型

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*,但我不知道如何处理这对我的构造函数和获取/ setter方法。

+1

'我已经想出了char [2] <=> char *'不是真的。 – Rapptz 2013-04-09 23:23:45

+0

但我认为C++编译器是char [2]相当于char *?!我真的不知道如何初始化这个构造函数和获取者... – vicR 2013-04-09 23:30:32

+1

数组和指针是*非常*不同的东西。阅读[comp.lang.c常见问题](http://www.c-faq.com/)的第6部分; C和C++在这方面的规则基本相同。 – 2013-04-09 23:37:21

回答

12

在C++中的原始数组是一种讨厌和充满危险。这就是为什么除非你有很好的理由,你应该使用std::vectorstd::array

首先,像其他人所说的那样,char[2]char*不一样,或者至少不是通常的。 char[2]char的大小2阵列,而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::string)。

2

当一个函数想要一个数组作为参数时,它会得到一个指向数组第一个元素的指针。该指针不能用于初始化数组,因为它是一个指针,而不是数组。

您可以编写接受引用到数组作为参数的函数:

void i_dont_accept_pointers(const char (array&)[2]) {} 

是这里的问题,这个数组引用不能用于初始化另一个数组。

class Foo { 
    char vars[2]; 
    Foo(const char (args&)[2]) 
    : vars(args) // This will not work 
    {} 
}; 

引入std::array到eliminiate这个和数组的其他问题C++ 11。在较旧的版本中,您将不得不遍历数组元素并单独复制它们或使用std::copy

相关问题