c++,类成员,string类型数组的初始化问题
代码如下classsupplier:publicpeople//people只是一个抽象类{private:stringmed[10];stringname;string...
代码如下
class supplier: public people //people只是一个抽象类
{
private:
string med[10];
string name;
string add;
public:
supplier();
supplier(string,string);
virtual void show() ;
virtual void set() ;
};
supplier::supplier()
{
med[10]={"x","x","x","x","x","x","x","x","x","x"}; //出问题的语句
name='x';
add='x';
}
error C2059: 语法错误 : “{”
error C2143: 语法错误 : 缺少“;”(在“{”的前面)
error C2143: 语法错误 : 缺少“;”(在“}”的前面)
尝试把错误语句换成这个:
for (int i=0;i<10;i++)
{
med[i]="x";
}
然后编译通过了,但是调试的时候没有赋值成功
求前辈解答疑惑。。。 展开
class supplier: public people //people只是一个抽象类
{
private:
string med[10];
string name;
string add;
public:
supplier();
supplier(string,string);
virtual void show() ;
virtual void set() ;
};
supplier::supplier()
{
med[10]={"x","x","x","x","x","x","x","x","x","x"}; //出问题的语句
name='x';
add='x';
}
error C2059: 语法错误 : “{”
error C2143: 语法错误 : 缺少“;”(在“{”的前面)
error C2143: 语法错误 : 缺少“;”(在“}”的前面)
尝试把错误语句换成这个:
for (int i=0;i<10;i++)
{
med[i]="x";
}
然后编译通过了,但是调试的时候没有赋值成功
求前辈解答疑惑。。。 展开
2个回答
展开全部
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]的值打出来,应该是可以的
比如 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]的值打出来,应该是可以的
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询