C++编程,有关类和数组思想的编程题

2025-03-25 16:53:26
推荐回答(3个)
回答1:

==================================================================
//VS2005调试通过
//注意:指针调用成员函数时,要使用 "->"; 对象调用成员函数时,要使用 "."
#include "stdafx.h"
#include
#include
#include "Test.h"

int _tmain(int argc, _TCHAR* argv[])
{
//因为类Test没有无参数的构造函数,所以只能用指针数组.

int array[5][2]= { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };

Test *pToy[5];

for (int i=0; i<5; i++)
{
pToy[i] = new Test(array[i][0], array[i][1]);
}

for (int i=0; i<5; i++)
{
std::cout << "pToy[ " << i << " ].num=" << pToy[i]->get_quan() << ", pToy[ " << i << " ].price= " << pToy[i]->get_price() << std::endl;
}

system("PAUSE");
return 0;
}

回答2:

toy mytoys[5];
mytoys[0] = new toy(1,3);
mytoys[1] = new toy(1,3);
mytoys[2] = new toy(1,3);
mytoys[3] = new toy(1,3);
mytoys[4] = new toy(1,3);//也可使用循环实现,看你具体有什么用途
for(int i = 0;i<5;i++)
{
out< out<}

回答3:

因为类toy没有无参数的构造函数,所以只能用指针数组.
int array[5][2]= {
{1, 2},
{3, 4},
{5, 6},
{7, 8},
{9, 10}
}
toy *pToy[5];
for (int i=0; i<5; i++)
{
pToy = new toy(array[i][0], array[i][1]);
}

for (int i=0; i<5; i++)
{
printf("pToy[%d].num=%d, pToy[%d].price=%d\n", i, pToy[i].get_quan(), i, pToy[i].get_price());
}