C++mid102_2
user_3763047219
c_cpp
a year ago
1.6 kB
0
Indexable
Never
#include <iostream> using namespace std; int num =1; class A{ public: //static int num; A():id(num){ name = id; num++; cout<<"Constructor: Obj "<<id<<" of type A. Name is"<<name<<endl; } //A(const A &a):id(1){cout<<"hiiii"<<endl;} ~A(){cout<<"Destructor: Obj "<<id<<" of type A. Name is"<<name<<endl; } const int id; int name; }; //int A::num=1; class B : public A{ public: B():id(num){ name = id; num++; cout<<"Constructor: Obj"<<id<<" of type B. Name is"<<name<<endl; } ~B(){cout<<"Destructor: Obj"<<id<<" of type B. Name is"<<name<<endl; } const int id; int name; }; //一開始(id,name): o1(1,1) o2(3,3) void swap1(A o1, B o2){ A tmp = o1; cout<<&o1<<endl; cout<<&tmp<<endl; cout<<tmp.id<<endl; o1.name = o2.name; o2.name = tmp.name; } //解構順序: tmp(1,1)->o1(1,3)->o2(3,1)(B->A) void swap2(A &o1, B &o2){ A tmp = o1; o1.name = o2.name; o2.name = tmp.name; } int main(){ A o1; B o2; cout<<o1.id<<" "<<o1.name<<endl; cout<<o2.id<<" "<<o2.name<<endl; swap1(o1, o2); cout<<o1.id<<" "<<o1.name<<endl; cout<<o2.id<<" "<<o2.name<<endl; { static A o3; swap2(o3,o2); cout<<o1.id<<" "<<o1.name<<endl; cout<<o2.id<<" "<<o2.name<<endl; cout<<o3.id<<" "<<o3.name<<endl; } //程式結束時解構順序:依照變數建立的順序,由後往前倒回去解 //先解子類別再解父類別 //static最後解 }