详情见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"<<<"called\n"; company=co; if(n<0) { std::cout<<"Number of shares can't be negative;"< <<"shares set to 0.\n"; } else { shares=n; } share_val=pr; set_tot(); } Stock::~Stock() { std::cout<<"Bye,"< <<"!\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"<<<"called\n"; company=co; if(n<0) { std::cout<<"Number of shares can't be negative;"< <<"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 usingNankSmartcalledCompany: NankSmart shares: 12 Share price: 20.000 total worth :240.00Constructor usingBoffo ObjectscalledCompany: Boffo Objects shares: 2 Share price: 2.000 total worth :4.00Assigning stock1 to stock2 :Listening stock1 and stock2: Company: NankSmart shares: 12 Share price: 20.000 total worth :240.00Company: NankSmart shares: 12 Share price: 20.000 total worth :240.00Using a constructor to reset an objectConstructor usingNifty FoodscalledBye,Nifty Foods!Revised stock1:Company: Nifty Foods shares: 10 Share price: 50.000 total worth :500.00DoneBye,NankSmart!Bye,Nifty Foods!Process finished with exit code 0