如果構造函數用於分配內存。構造函數調用分配內存?
在下面的程序中,它不起作用。 見
#include <iostream>
using namespace std;
class Demo
{
int i;
public:
Demo()
{
cout<<"\nDefault contructor called";
}
Demo(int x)
{
i = x;
cout<<"\nParameter contructor called";
}
void Display()
{
cout<<endl<<"i = "<<i<<endl;
}
};
int main()
{
Demo *demo = new Demo[5]; // = {1,2,3,4,5};
int i;
cout<<endl<<endl<<"First time";
cout<<endl<<"Addresses are "<<endl;
for(i=0;i<5; i++)
{
cout<<endl<< &demo[i];
}
cout<<endl<<endl<<"first time assigning values";
for(i=0;i<5; i++)
{
demo[i]= i;
}
cout<<endl<<endl<<"\nAfter first assignment";
cout<<endl<<"Addresses are "<<endl;
for(i=0;i<5; i++)
{
cout<<endl<< &demo[i];
}
cout<<endl<<endl<<"Second time assigning values";
for(i=0;i<5; i++)
{
demo[i]= i+5;
}
cout<<endl<<endl<<" After Second assignment ";
cout<<endl<<"Addresses are "<<endl;
for(i=0;i<5; i++)
{
cout<<endl<< &demo[i];
}
for(i=0;i<5; i++)
{
demo[i].Display();
}
return 0;
}
輸出:
Default contructor called Default contructor called Default contructor called Default contructor called Default contructor called First time Addresses are 0x8281008 0x828100c 0x8281010 0x8281014 0x8281018 first time assigning values Parameter contructor called Parameter contructor called Parameter contructor called Parameter contructor called Parameter contructor called After first assignment Addresses are 0x8281008 0x828100c 0x8281010 0x8281014 0x8281018 Second time assigning values Parameter contructor called Parameter contructor called Parameter contructor called Parameter contructor called Parameter contructor called After Second assignment Addresses are 0x8281008 0x828100c 0x8281010 0x8281014 0x8281018 i = 5 i = 6 i = 7 i = 8 i = 9
這裏的構造函數被調用三個時間和內存地址是相同的,意味着它不分配新的內存,並使用相同的地址。爲什麼?
爲什麼構造函數調用多次?
這意味着所有這三個時間稱爲contructer被其他物體(臨時對象)調用。是嗎?? – user2814127
@ user2814127:除第一組以外的所有內容。 –
你想說什麼。我不明白.. – user2814127