2011-12-21 131 views
1

我有一個單變量類,其中每個其他類實例將使用一個變量。 現在我想在我的單例類中放一個函數,說「GetReference」。常量指針返回參考

  1. 是否可以返回一個變量的引用?如果是這樣,我該如何返回變量的引用?
  2. 如何讓其他人只使用而不是修改或刪除變量。請問const適合我的情況嗎?

回答

2

1)上的變量返回一個引用,使用這種語法:

int& getARefOnDummy() 
{ 
    return dummy; 
} 

2)向返回一個const REF(將不能夠被修改或刪除),使用這種語法:

const int& getARefOnDummy() 
{ 
     return dummy; 
} 
0

const修飾符將爲您工作。在以下示例中,實例/靜態變量x將無法​​被調用getReference的任何內容修改。

const int& Singleton::getReference() const 
{ 
    return x; 
} 
0

嚴格地說const修飾符可以被轉出並且被修改。按照價值迴歸是比內部變量引用更安全更好的選擇。

如果按值返回很昂貴(例如返回一個大類的對象),委託模式可以與簡單的包裝類和對實現的私有引用一起使用。

0

你可以返回一個引用,但前提是它是靜態的或者是對象的一部分(即沒有局部變量)。

您也可以返回一個參考類的對象:

class Singleton 
{ 
private: 
    static Singleton *singleton = 0; 
    Singleton() // making the constructor private keeps others from creating their own instance 
    { 
    } 

    ~Singleton() // making the destructor private keeps others from destroying their instance on their own 
    { 
    } 
public: 
    static Singleton *GetPtr(void) 
    { 
     if(!singleton) 
      singleton = new Singleton(); 
     return singleton; 
    } 

    static Singleton &GetRef(void) 
    { 
     return *GetPtr(); // dereference the pointer 
    } 

    static void Free(void) 
    { 
     if(!singleton) 
      return; 
     delete singleton; 
     singleton = 0; 
    } 
} 

你還可返回一個常量指針和/或引用,這取決於你想與你的類做什麼(我不知道你是否只想讓別人刪除或修改)。請記住,有辦法欺騙(const_cast<>())。

0
#include <stdio.h> 
using namespace std; 
//This is the class, which I want to keep others to delete or modify 
class Ref{ 
public: 
    int X; 
}; 


class SingleTon{ 

private: 
    static Ref reference; 
public: 
    SingleTon(){ 
    // reference = new Ref(); 
    } 
    static const Ref& getReference(){return reference;} 
}; 

int main(){ 
    Ref * ptr = SingleTon::getReference(); 
} 

如果我說單身:: getReference(),我應該得到類文獻的refernce,使每個人都應該只使用它,但不能修改內容或刪除指針。