why i can't assign I[5] ?
#include <iostream.h>
class A{
private:
int x,y ;
public:
A(int a=0,int b=0){y=b;x=a;}
void init(int a,int b){x=a;y=b;}
void show(){cout<<x<<" "<<y<<endl;}
};
void main()
{
A l[5]={(1,1),(2,2),(3,3),(4,4),(5,5)};
A *p;
p=l;
l[3].init(8,3);
p->init(3,4);
for(int i=0;i<5;i++)
(*(p+i)).show();
}
when i execute this code,I[0] was shown (1.0),but I assign it (1,1),i[0] was not assigned.so was i[1],i[2]...
What can i do to assign i[5]?thanks very much.
Solution exploiting struct-like behaviour
[Y: Solution exploiting struct-like behaviour]
What the OP needs to do is:
1.Change the "private" to public. If you need to initialize the class member from an array, it needs to be accessible so you can't hide with "private".
2.Remove any constructor you declared. The compiler will decide how to initialize the object, not you.
3.Change the round bracket in your parameter list to curly bracket.
This is how the working code looks like:
Code:
//...
class A
{
public:
int x;
int y;
public:
void init(int a,int b){x=a;y=b;}
void show() {printf("%d %d\r\n", x, y);}
};
int main(int argc, char* argv[])
{
A l[5] = {{1,1},{2,2},{3,3},{4,4},{5,5}};
//...
}
[Yves : cleaned up the post a bit]