今天遇到一个问题,直接上代码
// 我要申请一个类的数组
class Acount{
Account() ;
Account(string , string , float ) ;
static float GetInterestRate(float );
};
int main(){
//中间省略
//我是这样写的
int t;
Account *p;
p=new Account[t];//这里已经初始化了,调用了Account()的构造函数
//但是,如果要赋值怎么办呢?
//构造函数不是不能调用第二次么?
/*
* Account dd;
dd.Account("","",10);//这个就会报错的,因为第二次调用
*/
for (j = 0; j < t; j++) {
p[j].GetInterestRate(float);//说明类已经申请出来空间了
p[j] = Account(string, string, float);//这里调用了是一个没有名字的构造 Account(no, name, balance),通过拷贝构造,复制给了p[j];
}
//但是在网上看见一个代码这样写的,当时觉得很困惑,为什new可以写在后面呢?后面发现
typedef Account* qq;//实际上是定了一个别名,这个别名是一个类指针,* Account(),他的名字叫qq
qq *mmm[10];//这里只是建立了十个指针,相当于Account *p[10],所以根本没有调用构造函数
//假如不是10,是一个未知数,就会报错,它不是动态的数组!!!
for (j = 0; j < 10; j++) {
mmm[i]=new Account(string, string, float);
}
//省略
return 0;
}