关于析构函数和构造函数何时调用的小例子

Posted SuperHero

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于析构函数和构造函数何时调用的小例子相关的知识,希望对你有一定的参考价值。

详情见C++ PrimerPlus第十章

省略其他函数,将构造函数和析构函数写出来

Stock::Stock() //default constructor
{
std::cout<<"Default constructor called\n";
company="no name";
shares=0;
share_val=0;
total_val=0;
}

Stock::Stock(const std::string&co,long n,double pr)
{
std::cout<<"Constructor using"<<co<<"called\n";
company=co;
if(n<0)
{
std::cout<<"Number of shares can‘t be negative;"<<company<<"shares set to 0.\n";

}
else
{
shares=n;
}
share_val=pr;
set_tot();
}

Stock::~Stock()
{
std::cout<<"Bye,"<<company<<"!\n";
}

正常情况下析构函数和构造函数一般没有cout语句,这里为了显示出他何时被调用,加上了输出语句。
int main()
{
{
using std::cout;
cout<<"Using constructors to creat new objects\n";
Stock stock1("NankSmart",12,20);
stock1.show();
Stock stock2("Boffo Objects",2,2);//调用时
// 直接调用了构造函数 即下列函数

/*Stock::Stock(const std::string&co,long n,double pr)
{
std::cout<<"Constructor using"<<co<<"called\n";
company=co;
if(n<0)
{
std::cout<<"Number of shares can‘t be negative;"<<company<<"shares set to 0.\n";

}
else
{
shares=n;
}
share_val=pr;
set_tot();
}
因此编译后有如下语句:
Constructor usingBoffo Objectscalled
Company: Boffo Objects shares: 2
Share price: 2.000 total worth :4.00
* */

     stock2.show();

cout<<"Assigning stock1 to stock2 :\n";
stock2=stock1;
cout<<"Listening stock1 and stock2: \n";
stock1.show();
stock2.show();

cout<<"Using a constructor to reset an object\n";
stock1=Stock("Nifty Foods",10,50);
//这里调用了析构函数,有如下语句 "Bye,Nifty Foods!"
cout<<"Revised stock1:\n";
stock1.show();
cout<<"Done\n";
//最后结束的时候,全部对象结束调用,所以有调用了两个对象的析构函数
//有如下语句
//Bye,NankSmart!
//Bye,Nifty Foods!
}
}
最后是编译后的结果(有些遍以前可能不同)

Using constructors to creat new objects
Constructor usingNankSmartcalled
Company: NankSmart shares: 12
Share price: 20.000 total worth :240.00
Constructor usingBoffo Objectscalled
Company: Boffo Objects shares: 2
Share price: 2.000 total worth :4.00
Assigning stock1 to stock2 :
Listening stock1 and stock2:
Company: NankSmart shares: 12
Share price: 20.000 total worth :240.00
Company: NankSmart shares: 12
Share price: 20.000 total worth :240.00
Using a constructor to reset an object
Constructor usingNifty Foodscalled
Bye,Nifty Foods!
Revised stock1:
Company: Nifty Foods shares: 10
Share price: 50.000 total worth :500.00
Done
Bye,NankSmart!
Bye,Nifty Foods!

Process finished with exit code 0

以上是关于关于析构函数和构造函数何时调用的小例子的主要内容,如果未能解决你的问题,请参考以下文章

为啥C++里面,析构函数会被调用两次

C++类调用构造函数 和 析构函数的顺序

C++类调用构造函数 和 析构函数的顺序

C++关于类结构体大小和构造顺序析构顺序的测试。

C++关于类结构体大小和构造顺序析构顺序的测试。

C++关于类结构体大小和构造顺序析构顺序的测试。