析构函数有一点不理解
程序代码:
stock.c: #include "stdafx.h" #include "stock.h" #include <iostream> Stock::Stock() { std::cout<<"Default constructor called\n"; company="no name"; shares=0; share_val=0.0; total_val=0.0; } Stock::Stock(const std::string &co,long n,double pr) { std::cout <<"Constructor using"<<co<<"called\n"; company=co; shares=n; share_val=pr; set_tot(); } Stock::~Stock() { std::cout<<"bye,"<<company<<"!\n"; } void Stock::buy(long num,double price) { shares+=num; share_val=price; set_tot(); } void Stock::sell(long num,double price) { shares-=num; share_val=price; set_tot(); } void Stock::update(double price) { share_val=price; set_tot(); } void Stock::show() { using std::cout; using std::ios_base; ios_base::fmtflags orig=cout.setf(ios_base::fixed,ios_base::floatfield); std::streamsize prec =cout.precision(3); cout<<"Company: "<<company <<" Shares: "<<shares<<'\n'; cout<<" Share price:$"<<total_val<<'\n'; cout.precision(2); cout<<" Total Worth:$"<<total_val<<'\n'; cout.setf(orig,ios_base::floatfield); cout.precision(prec); } stock.h: #ifndef STOCK_H #define STOCK_H #include <string> class Stock { public: Stock(); Stock(const std::string &co,long n=0,double pr=0.0); ~Stock(); void buy(long num,double price); void sell(long num,double price); void update(double price); void show(); private: std::string company; long shares; double share_val; double total_val; void set_tot() {total_val=shares*share_val;} }; #endif main: #include "stdafx.h" #include <iostream> #include "stock.h" #include <stdio.h> int main() { { using std::cout; cout<<"Using constructors to create new objects\n"; Stock stock1("Nanosmart",12,20.0); stock1.show(); Stock stock2=Stock("Boffo Objects",2,2.0); stock2.show(); cout<<"Assigning stock1 to stock2:\n"; stock2=stock1; cout<<"Listing stock1 and stock2\n"; stock1.show(); stock2.show(); cout<<"Using a constructor to reset an object\n"; stock1=Stock("Nifty Foods",10,50.0); cout<<"Revised stock1\n"; stock1.show(); cout<<"Done\n"; } return 0; }
结果:
程序代码:
Using constructors to create new objects Constructor usingNanosmartcalled Company: Nanosmart Shares: 12 Share price:$240.000 Total Worth:$240.00 Constructor usingBoffo Objectscalled Company: Boffo Objects Shares: 2 Share price:$4.000 Total Worth:$4.00 Assigning stock1 to stock2: Listing stock1 and stock2 Company: Nanosmart Shares: 12 Share price:$240.000 Total Worth:$240.00 Company: Nanosmart Shares: 12 Share price:$240.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:$500.000 Total Worth:$500.00 Done bye,Nanosmart! bye,Nifty Foods! 请按任意键继续. . .
1:sotck2=stock1 这里传递的是数组的值还是数组的地址
2:stock1=Stock("Nifty Foods"....)这一步为什么出现的是 Bye,Nifty Foods! 我理解应该是Bye,Nanosmart!