[英]How to initialize an array in a class constructor?
Working in Xcode on Mac OS X Leopard in C++: 使用C ++在Mac OS X Leopard上使用Xcode :
I have the following code: 我有以下代码:
class Foo{
private:
string bars[];
public:
Foo(string initial_bars[]){
bars = initial_bars;
}
}
It does not compile and throws the following error: 它不编译并抛出以下错误:
error: incompatible types in assignment of 'std::string*' to 'std::string [0u]'
I notice that removing the line bars = initial_bars;
我注意到删除了line
bars = initial_bars;
solves the problem. 解决了这个问题。 It seems like I am not doing the assignment correctly.
好像我没有正确地完成任务。 How could I go about fixing this problem?
我怎么能解决这个问题呢?
EDIT: 编辑:
The variable bars is an array of strings. 变量条是一个字符串数组。 In the main function I initialize it like this:
在main函数中,我将它初始化为:
string bars[] = {"bar1", "bar2", "bar3"};
But it can contain an arbitrary number of members. 但它可以包含任意数量的成员。
Arrays behave like const pointers, you can't assign pointers to them. 数组的行为类似于const指针,您无法为它们指定指针。 You also can't directly assign arrays to each other.
您也无法直接为彼此分配数组。
You either 你要么
bar
s you get and initialize your member array with its contents bar
并用你的内容初始化你的成员数组 std
container like std::vector
std
容器的引用,如std::vector
It is possible to "value-initialize" array members as follows: 可以按如下方式“值初始化”数组成员:
class A {
public:
A ()
: m_array () // Initializes all members to '0' in this case
{
}
private:
int m_array[10];
};
For POD types this is important as if you don't list 'm_array' in the member initialization list then the array elements will have indeterminate values. 对于POD类型,这很重要,就好像您没有在成员初始化列表中列出'm_array'那样数组元素将具有不确定的值。
In general it's better to initialize members in the member-initialization-list, otherwise the members will be initialized twice: 通常,最好在member-initialization-list中初始化成员,否则成员将初始化两次:
A (std::vector<int> const & v)
// : m_v () // 'm_v' is implicitly initialized here
{
m_v = v; // 'm_v' now assigned to again
}
More efficiently written as: 更有效地写作:
A (std::vector<int> const & v)
: m_v (v)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.