【C++ grammar】对象指针、对象数组、函数参数
目錄
- 1、Object Pointer & Dynamic Object
- 1. Accessing Object Members via Pointers
- 2. Creating Dynamic Objects on Heap
 
- 2、Array of Objects
- 聲明方式
 
- 3、Passing Objects to Functions
- 1、Objects as Function Arguments (對象作為函數參數)
- 2. Objects as Function Return Value(對象作為函數返回值)
- 3. Objects Pointer as Function Return Value(對象指針作為函數返回值)
- 4. Objects Reference as Function Return Value(對象引用作為函數返回值)
 
1、Object Pointer & Dynamic Object
1. Accessing Object Members via Pointers
Object pointers can be assigned new object names
 Arrow operator -> : Using pointer to access object members
2. Creating Dynamic Objects on Heap
Object declared in a function is created in the stack, When the function returns, the object is destroyed 。
 To retain the object, you may create it dynamically on the heap using the new operator.
2、Array of Objects
聲明方式
1、
Circle ca1[10];2、用匿名對象構成的列表初始化數組
Circle ca2[3] = { // 注意:不可以寫成: auto ca2[3]= 因為聲明數組時不能用autoCircle{3}, Circle{ }, Circle{5} };3、聲明方式3
 用C++11列表初始化,列表成員為隱式構造的匿名對象
4、 聲明方式4
 用new在堆區生成對象數組
上述代碼第4行若是改為 delete [] p1,會發生什么情況?
 
3、Passing Objects to Functions
1、Objects as Function Arguments (對象作為函數參數)
You can pass objects by value or by reference. (對象作為函數參數,可以按值傳遞也可以按引用傳遞)
(1) Objects as Function Return Value(對象作為函數參數) // Pass by value void print( Circle c ) {/* … */ }int main() {Circle myCircle(5.0);print( myCircle );/* … */ } (2) Objects Reference as Function Return Value(對象引用作為函數參數) void print( Circle& c ) {/* … */ }int main() {Circle myCircle(5.0);print( myCircle );/* … */ } (3) Objects Pointer as Function Return Value(對象指針作為函數參數) // Pass by pointer void print( Circle* c ) {/* … */ }int main() {Circle myCircle(5.0);print( &myCircle );/* … *、 }
 
2. Objects as Function Return Value(對象作為函數返回值)
// class Object { ... }; Object f ( /*函數形參*/ ){// Do somethingreturn Object(args); } // main() { Object o = f ( /*實參*/ ); f( /*實參*/ ).memberFunction();3. Objects Pointer as Function Return Value(對象指針作為函數返回值)
// class Object { ... }; Object* f ( Object* p, /*其它形參*/ ){// Do somethingreturn p; } // main() { Object* o = f ( /*實參*/ ); // 不應該delete o盡可能用const修飾函數返回值類型和參數除非你有特別的目的(使用移動語義等)。
 const Object* f(const Object* p, /* 其它參數 */) { }
4. Objects Reference as Function Return Value(對象引用作為函數返回值)
// class Object { ... }; class X {Object o;Object f( /*實參*/ ){// Do somethingreturn o;} } 可行的用法2 // class Object { ... }; Object& f ( Object& p, /*其它形參*/ ){// Do somethingreturn p; } // main() { auto& o = f ( /*實參*/ ); f( /*實參*/ ).memberFunction();用const修飾引用類型的函數返回值,除非你有特別目的(比如使用移動語義)
 const Object& f( /* args */) { }
 關于指針與引用的差別,請看這篇文章:
 C++中引用和指針的區別
大概來講:
 1、因此如果你有一個變量是用于指向另一個對象,但是它可能為空,這時你應該使用指針;如果變量總是指向一個對象,i.e.,你的設計不允許變量為空,這時你應該使用引用。
 2、引用不可以改變指向,但是指針可以改變指向,而指向其它對象。
對ref的++操作是直接反應到所指變量之上,對引用變量ref重新賦值"ref=j",并不會改變ref的指向,它仍然指向的是i,而不是j。理所當然,這時對ref進行++操作不會影響到j。
總結
以上是生活随笔為你收集整理的【C++ grammar】对象指针、对象数组、函数参数的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 颐和园几点关门不让进了
- 下一篇: 猎头局中局剧情介绍
