我遇到了这个错误,这是我在课堂上的代码并出现错误。
在没有类的情况下,数组工作正常,但是当我使用类时,出现了错误
class books{
string author[20], title[20], publisher[20];
float price[20];
int stock_position[20];
public:
books(){
author[20] = {"author1", "author2", "author3", "author4", "author5", "author6", "author7", "author8", "author9","author10"};
title[20] = {"book1", "book2", "book3", "book4", "book5", "book6", "book7", "book8", "book9", "book10"};
publisher[20] = {"publisher1,", "publisher2", "publisher3", "publisher4", "publisher5", "publisher6", "publisher7", "publisher8", "publisher9", "publisher10",};
price[20] = {12,23,34,45,56,67,67,78,45};
stock_position[20] = {7,6,21,23,14,5,12,32,43,06};
}
input(string,string);
find();
buy();
edit();
display();
};
错误:
[Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11 [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11 [Error] no match for 'operator=' (operand types are 'std::string {aka std::basic_string<char>}' and '<brace-enclosed initializer list>')
答案 0 :(得分:1)
那不是您初始化类成员的方式,而是分配。成员初始化仅在 ctor-initializer-list 中进行,而不会在构造函数主体中进行。
这也是您要实现的语法错误,并且在语义上是非法的。没有类似于 list-initialization 的“列表分配”语法。
author[20]
不存在,有效的索引是从0
到19
。如果确实存在,它将仅引用一个string
而不是整个数组。
使用 ctor-initializer-list 的正确语法如下(大括号初始化也需要C ++ 11, ctor-initializer-list中没有列表初始化在以前的C ++版本中)
class books
{
std::string author[20], title[20], publisher[20];
float price[20];
int stock_position[20];
public:
books()
: author{"author1", "author2", "author3", "author4", "author5", "author6", "author7", "author8", "author9","author10"}
, title{"book1", "book2", "book3", "book4", "book5", "book6", "book7", "book8", "book9", "book10"}
, publisher{"publisher1,", "publisher2", "publisher3", "publisher4", "publisher5", "publisher6", "publisher7", "publisher8", "publisher9", "publisher10"}
, price{12,23,34,45,56,67,67,78,45}
, stock_position{7,6,21,23,14,5,12,32,43,06}
{
}
};
在C ++ 11之前,尽管为std::array
和辅助函数提供了一种解决方法,但在为数组成员指定初始化程序时还是很不走运。