c++,类成员,string类型数组的初始化问题

2024-12-01 08:19:51
推荐回答(2个)
回答1:

med[10]={"x","x","x","x","x","x","x","x","x","x"};这样的赋值只有在定义数组的时候同时初始化才可以
比如 string med[10]={"x","x","x","x","x","x","x","x","x","x"};
对于类成员,早被定义了,所以这样赋值是非法的
不过

for (int i=0;i<10;i++)
{
med[i]="x";
}
这种方法应该是可行的
验证程序
#include
#include
using namespace std;
int main()
{
string a[3] ;
for(int i = 0; i < 3; i ++)
a[i] = "x";
for(int i = 0; i < 3; i ++)
cout << i << ": " << a[i] << endl;
return 0;
}

输出
0: x
1: x
2: x
你说的没赋值成功是怎么知道的?应该是其他地方有问题
你可以在赋值后,把med[i]的值打出来,应该是可以的

回答2:

  在构造函数体里面已经不是初始化了,是赋值 ”med[10]={"x","x","x","x","x","x","x","x","x","x"};
“ 整体赋值好像不符合c++语言规则