原創請註明出處:
我們這裡主要討論建構函式的建構函式的分類和其呼叫時機
測試類如下:
namespace test_n
void printanys(test& p)
test(
int c_a,
int c_b)
//有參建構函式
test(
int c_a)
test(
const test &m)
//copy 建構函式
void print(
)~test(
)void plus20()/
/3-3
void printany(test p)
void printany(test* p)
void printanys(test& p)
//3-4
test test34(test p)
//test new
test& testy(test p)
//返回為區域性的匿名物件的引用,不能做左值不能用於初始化引用
test& testm()/
/返回是引用記憶體空間永久可以作為左值
private
:int a;
int b;};
}//int main()/
/以下是函式返回引用作為左值和右值的測試//
--函式返回用用分為以下//
--返回為區域性變數
//可以用int a = test(
);來接
//不可以用int &a = test(
);來接
//不能做左值//
//--返回為全域性或者靜態變數
//可以用int a = test(
);來接
//可以用int &a = test(
);來接
//可以當左值//
//a=test(
) 1 變數來接//
int&a=test(
) 2 初始引用來接
//test(
)=b 3 作為左值//
int& test()/
/int main12()
執行結果:
無參構造函式呼叫 adress: 0x7ffc20853490
1771925424 32660
有參構造函式呼叫 adress: 0x7ffc208534a0
1 2有參構造函式呼叫 adress: 0x7ffc208534b0
100 0
有參構造函式呼叫 adress: 0x7ffc208534c0
100 100
copy構造函式呼叫 adress: 0x7ffc208534d0
1 2copy構造函式呼叫 adress: 0x7ffc208534e0
100 100
copy構造函式呼叫 adress: 0x7ffc208534f0
匿名物件生成
100 100
析構函式呼叫 adress: 0x7ffc208534f0 1
copy構造函式呼叫 adress: 0x7ffc20853500
copy構造函式呼叫 adress: 0x7ffc20853510
析構函式呼叫 adress: 0x7ffc20853510 2
析構函式呼叫 adress: 0x7ffc20853500 3
copy構造函式呼叫 adress: 0x7ffc20853530
copy構造函式呼叫 adress: 0x7ffc20853520
析構函式呼叫 adress: 0x7ffc20853530 4
120 120
copy構造函式呼叫 adress: 0x7ffc20853540
copy構造函式呼叫 adress: 0x7ffc20853550
析構函式呼叫 adress: 0x7ffc20853550 5
析構函式呼叫 adress: 0x7ffc20853540 6
120 120
析構函式呼叫 adress: 0x7ffc20853520 7
析構函式呼叫 adress: 0x7ffc208534e0 8
析構函式呼叫 adress: 0x7ffc208534d0 9
析構函式呼叫 adress: 0x7ffc208534c0
10析構函式呼叫 adress: 0x7ffc208534b0
11析構函式呼叫 adress: 0x7ffc208534a0
12析構函式呼叫 adress: 0x7ffc20853490
C 拷貝構造函式呼叫時機
class a 傳入乙個字串代表變數的名字 a string n name n a 拷貝建構函式a const a a 過載 運算子 a operator const a a friend ostream operator ostream os,const a a private string na...
C 拷貝建構函式的呼叫時機
include iostream using namespace std class test2 test2 int a test2 int a,int b 有參建構函式 兩個引數 test2 析構函式 test2 const test2 obj void printf void main31 in...
C 拷貝建構函式的呼叫時機
當以拷貝的方式初始化物件時會呼叫拷貝建構函式,這裡需要注意兩個關鍵點,分別是以拷貝的方式和初始化物件 1.初始化物件 初始化物件是指,為物件分配記憶體後第一次向記憶體中填充資料,這個過程會呼叫建構函式,物件被建立後必須立即初始化。也就是說只要建立物件就會呼叫建構函式。2.初始化和賦值的區別 初始化和...