若想要以非物件的預設建構子去初始化一個物件陣列時
要怎麼做呢
請參考底下的程式碼
#include
#include
#include
#include
using namespace std;
class car {
int price;
string name;
public:
//car():price(100), name("ford"){}
car();
car(int, string);
void show();
};
car::car()
{
price = 100;
name = "ford";
}
car::car(int i, string str)
{
price = i;
name = str;
}
void car::show()
{
cout << price << " " << name << endl;
}
int main()
{
car car1, car2(120, "bmw");
//default constructor
car1.show();
//initial by manual
car2.show();
//object array and initial by manual
car car3[5] = {car(1, "bmw z1"), car(2, "bmw z2"), car(3, "bmw z3"),
car(4, "bmw z4"), car(5, "bmw z5")};
//using vector to create 101 objects with the same value
vectorcar4;
for(int i = 0; i != 5; i++) {
car3[i].show();
}
for(int i = 0; i != 10; ++i) {
car4.push_back(car2);
car4[i].show();
}
//The following two ways are wrong!
//car *ptr = new car(111, "benz")[3];
//car *ptr = new car[3](111, "benz");
return 0;
}
輸出結果如下:
100 ford
120 bmw
1 bmw z1
2 bmw z2
3 bmw z3
4 bmw z4
5 bmw z5
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
結論是用 car array_car[5](1, "xx")
或是 car array_car(1,"xx")[5] 都是錯的 Orz
沒有留言:
張貼留言