C++中 ,结构体数组怎么利用构造函数初始化?

struct Rectangle {
public:
int w;
int l;
int area;
Rectangle(int a , int b ) {
l = a>b?a:b;
w = a>b?b:a;
area = a*b;
}
};

初始化2个Rectangle ,初始化为3,4;2,3.

第1个回答  2011-01-02
Rectangle rs[2] = { Rectangle(3, 4), Rectangle(2, 3)};

或者
Rectangle * rps[2] = {new Rectangle(3, 4), new Rectangle(2, 3)};
释放
for(int i i = 0; i < 2; i++)
delete rps[i];本回答被提问者采纳
第2个回答  2015-06-09
下面程序的功能是从文件data.txt中读取数据(数据格式如你所说的用空格隔开,且一行一组数据),并赋值在node这个结构体里面:
*/ #include <iostream.h> #include <afx.h> struct node
{ CString Name; CString ID; CString addr; };
void main() { CStdioFile file; node data[10];
int i = 0;
if(!file.Open("data.txt",CFile::modeRead))cout<<"file read error!<<endl;
else { CString s; while (file.ReadString(s)) { data[i].Name = s.Left(s.Find(" ")); s.Delete(0,s.Find(" ")+1);
data[i].ID = s.Left(s.Find(" "));
s.Delete(0,s.Find(" ")+1);
data[i++].addr = s; } } for (int j = 0;j<i;j++) { cout<<"Name:"<<data[j].Name<<"\tID:"<<data[j].ID<<"\tAddr:"<<data[j].addr<<endl; } }
第3个回答  2011-01-02
Rectangle rect1(3,4);
Rectangle rect2(2,3);

或者指针
Rectangle* pRect = new Rectangle(3, 4);
...
delete pRect;本回答被网友采纳
相似回答