c++,类成员,string类型数组的初始化问题
发布网友
发布时间:2022-04-25 18:52
我来回答
共2个回答
热心网友
时间:2023-10-08 14:13
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 <iostream>
#include <string>
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]的值打出来,应该是可以的
热心网友
时间:2023-10-08 14:14
在构造函数体里面已经不是初始化了,是赋值 ”med[10]={"x","x","x","x","x","x","x","x","x","x"};
“ 整体赋值好像不符合c++语言规则