java - C++返回对象的指针或者引用有什么区别?
阿神
阿神 2017-04-18 10:10:12
0
3
546
阿神
阿神

闭关修行中......

全部回覆(3)
Peter_Zhu

C++裡引用其實只是受限的指針,只是在語意上限制不能對引用這一受限的指針做一些指針能做的操作:重新賦值,拷貝,++,--(暫時還沒想到其他的),並限制不允許為空,以提高安全性,可以理解為是編譯器對指標的一種保護模式。

那麼,考慮什麼時候該使用引用,又什麼時候該使用指標呢?我認為有幾點:

  1. 引用優先

    凡是能用引用代替指標的都用引用。

  2. 指標是允許為空的,而引用不允許。

    const stock* top(...)
    {
        return NULL;
    }

    當然,這種情況下你還是可以堅持使用引用,然後空物件的情況下可以用throw exception的方式來表達:

    const stock& top(...)
    {
        throw null_top_stock_exception();
    }
  3. 合理使用語意暗示,指標暗示擁有(has),引用暗示關聯(use):

    car has a wheel

    class wheel {};
    class car
    {
        wheel* _wheel;
    public:
        car() : _wheel(NULL) {};
        void set_wheel(wheel* wheel) { _wheel = wheel; };
    };

    trip use a car:

    class trip
    {
        const car& _car
    public:
        trip(const car& car) : _car(car) {};
    };

    當然,也是有例外,如果在trip的生存週期裡,關聯的_car是要求可變的,那就只能使用指針了(因為引用不可以重新賦值):

    class trip
    {
        const car* _car
    public:
        trip(const car* car) : _car(car) {};
        void set_car(const car* car) : _car(car) { _car = car; };
    };

    否則,堅持使用引用的話,想更改_car的指向,就只能重新建構一個新的trip了。

  4. 容器中不可保存引用,只能用指標(我猜主要是因為引用被限制了重新賦值及拷貝操作):

    std::vector<car> cars;  // OK 
    std::vector<car*> cars; // OK
    std::vector<car&> cars; // ERROR
  5. 最後,隨時可以把引用轉換成指標:

    class maintainer
    {
    public:
        void maintain(car& car)
        {
            car* p = &car;
            // play with pointer 'p'
        }
    };

    但一定要注意情景,這裡car只是傳進來供maintain方法使用(引用暗示use關係),取指針操作雖然不優雅,尚可以接受,但千萬要注意把指針保存下來使用的情況:

    class maintainer
    {
        car* _last_car;
    public:
        void maintain(car& car)
        {
            car* _last_car = &car;
            // ...
        }
        void review_last_maintain()
        {
            // play with "_last_car"
        }
    };

    在退出maintain方法後,_last_car所指向的物件是很有可能會被釋放的。

伊谢尔伦

const講起來就是個無底洞
舉個引用的例子吧

#include <iostream>
#include<string>
using namespace std;

class Stu
{
public:
    Stu(string name, int age) // :name(name),age(age)
    {
        this->name = name;
        this->age = age;
    }
    Stu & Add()
        //Stu * const & Add()
    {
        this->age++;
        return *this; 
        // return this;//this 指针是const类型
    }
    void display()
    {
        cout << name << " : " << age << endl;
    }
private:
    string name;
    int age;
};
int main()
{
    Stu s("xiaoming", 20);
    s.display();
    s.Add().Add().Add().Add().Add();
    //Add函数返回引用的好处是,你可以进行连加或者比如运算符重载返回引用类型进行连等于运算 
    //s.Add()->Add()->Add()->Add();
    s.display();
    return 0;
}
巴扎黑

指標的話,允許return NULL,引用的話不行。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!