各位高手:我在控制台下,编了如下代码:#include <iostream>
using namespace std;
void main()
{
int a[3][2]; int i,j;
a[3][2]={ 2,1,8,3,4,4 };
for( i=0;i<3;i++)
for( j=0;j<2;j++)
cout<<a[i][j]<<endl;
}错误如下:
E:\aa\t1\a.cpp(9) : error C2059: syntax error : '{'
E:\aa\t1\a.cpp(9) : error C2143: syntax error : missing ';' before '{'
E:\aa\t1\a.cpp(9) : error C2143: syntax error : missing ';' before '}'
Error executing cl.exe.
不知是什么原因,请各位高手点拨。先谢了。
using namespace std;
void main()
{
int a[3][2]; int i,j;
a[3][2]={ 2,1,8,3,4,4 };
for( i=0;i<3;i++)
for( j=0;j<2;j++)
cout<<a[i][j]<<endl;
}错误如下:
E:\aa\t1\a.cpp(9) : error C2059: syntax error : '{'
E:\aa\t1\a.cpp(9) : error C2143: syntax error : missing ';' before '{'
E:\aa\t1\a.cpp(9) : error C2143: syntax error : missing ';' before '}'
Error executing cl.exe.
不知是什么原因,请各位高手点拨。先谢了。
for( j=0;j<2;j++)
cout<<a[i][j]<<endl;}
}
int a[][]={{1,2},{2,3},{4,5}}
using namespace std;
void main()
{
int a[3][2]={{2,1},{8,3},{4,4}}; int i,j;
// a[3][2]={{2,1},{8,3},{4,4}};
for( i=0;i<3;i++)
for( j=0;j<2;j++)
cout<<a[i][j]<<endl;
}
int a[3][2]={{1,2},{2,3},{4,5}}就这样!ok!
#include <iostream>
using namespace std;
void main()
{
int a[3][2]={ 2,1,8,3,4,4 }; int i,j;
//a[3][2]={ 2,1,8,3,4,4 };
for( i=0;i<3;i++)
for( j=0;j<2;j++)
cout<<a[i][j]<<endl;
}
1
8
3
4
4
Press any key to continue
using namespace std;
void main()
{
int i,j;
int a[3][2]={{2,1},{8,3},{4,4}};
for( i=0;i<3;i++)
for( j=0;j<2;j++)
cout<<a[i][j]<<endl;
}
可以通过.
2
1
8
3
4
4
Press any key to continue这个例子里两种定义int a[3][2]={{1,2},{2,3},{4,5}}
和 int a[3][2]={ 2,1,8,3,4,4 };
是等价的,都是对从a开始的连续6个地址(24字节)赋值。
我先定义了一个类:class CGrid
{
private:
public: CGrid();
~CGrid();
int position[4][2];
};然后,我这样:
CGrid grid;
grid.position[4][2]={ .....内略....};
这样分开(“定义”,“赋值”)。怎样才能坐到。对应到刚才控制台下的题,怎样分开定义。请高手指点。先谢了
我先定义了一个类:class CGrid
{
private:
public: CGrid();
~CGrid();
int position[4][2];
};然后,我这样:
CGrid grid;
grid.position[4][2]={ .....内略....};
因为这样赋值出错。不能这样,该怎样?
这样分开(“定义”,“赋值”)。怎样才能坐到。对应到刚才控制台下的题,怎样分开定义。请高手指点。先谢了
{
private:
public: CGrid();
~CGrid();
int position[4][2];
void InitPos(int *p)
{
int *t = &position[0][0];
for(int i=0;i<4*2;i++) *t++ = *p++;
};
};
int a[3];
a[]={1,2,3};
是不能实现的。
只能用 int a[3]={1,2,3};的格式.因为,
在int a[3]={1,2,3};中
"=" 并不是赋植运算符,而是一种赋初始值的记号,同样,
{1,2,3}也不是运算符.
所以,在不是定义变量的地方,
a[3]={1,2,3};会被当作执行语句,而且
a[3]被看作"a的第4个元素",而不表示"a有3个元素",
显然,语法错误就产生了。不仅如此,有些C语言,在{}里还不能有变量,
比如
int a=10;
int b[3]={a,a*2,a*3};也不允许。
using namespace std;
void main()
{
int a[3][2]={ 2,1,8,3,4,4 }; int i,j;
for( i=0;i<3;i++)
for( j=0;j<2;j++)
cout<<a[i][j]<<endl;
}
这样就可以了。
void InitPos(int *p)
{
int *t = &position[0][0];
for(int i=0;i<4*2;i++) *t++ = *p++;
};
这里的 p 干什么用的?
是为了支持新的库函数。但在#include <iosteram> 要加上 using namespace std; 名字空间。