2015-05-22 145 views
0

我需要從class stos的方法「pop」中的類信息獲取私有數據的訪問權限。我知道我可以使用修改嵌套函數的特殊方法,但我認爲它不像使用「朋友」那樣是elegnat。我想將外部方法作爲嵌套類的朋友,但是我得到的信息是「不能重載單獨返回類型所忽略的函數」。是否有可能做到這一點?嵌套類C++,如何使外部方法作爲嵌套類的朋友

class stos 
{ 
    class info 
    { 
     int x; 
     bool isGood; 
     friend info pop(); // warning: cannot overload functions distungished by return type alone 
    }; 
    static const int SIZE = 10; 
    int dane[SIZE]; 
    bool isEmpty; 
    bool isFull; 
    int *top; 
public: 
    stos(); 
    info pop(); 
    info push(int x); 
}; 

編輯:

stos::info stos::pop() 
{ 
    info objInfo; 
    if (isEmpty == true) 
    { 
     objInfo.isGood = false; 
     return objInfo; 
    } 

    objInfo.isGood = true; 
    objInfo.x = *top; 
    top--; 
    return objInfo; 

} 
+0

你用什麼編譯器?該代碼在VisualStudio GCC(從4.3到4.9)和最新的Clang ^^中編譯得很好。無論如何,你永遠不需要好的設計代碼中的「朋友」函數 – GameDeveloper

+0

@DarioOO它編譯得很好,但不會生成'stos :: pop'朋友,但是沒有定義全局函數'pop'。如果你嘗試'friend info stos :: pop()',那麼你會得到'錯誤:使用不完整類型'class stos''。 – vsoftco

+0

我知道。用戶發佈了一個代碼,它不會立即重現問題,如果我不知道如何通過顯示有問題的代碼片段來使用代碼,則無法提供更多幫助。 – GameDeveloper

回答

1

代碼編譯罰款但您可能想做到以下幾點:

#include <iostream> 
using namespace std; 

class stos 
{ 
class info 
{ 
     int x; 
     bool isGood; 
     friend class stos; //allow stos accessing private data of info 
     info pop(){} 
    }; 
    static const int SIZE = 10; 
    int dane[SIZE]; 
    bool isEmpty; 
    bool isFull; 
    int *top; 
public: 
    stos(); 
    info pop(){ 
     info a; 
     a.pop(); //calling here a private method 
    } 
    info push(int x); 


}; 

int main() { 
    // your code goes here 
    return 0; 
} 
3

您可以在stos開始申報info類,然後定義它後來。所以你可以改變你的班級的定義到這

class stos 
{ 
    class info; 
    ^^^^^^^^^^ Declare it here 

... rest of class 

public: 
    info pop(); 

private: 
    class info 
    { 
     int x; 
     bool isGood; 
     friend info stos::pop(); 
        ^^^^ Added surrounding class for overload resolution 
    }; //Define it here 
}; 

這應該停止錯誤。

+0

但是爲什麼我應該在「friend info stos :: pop()」中使用「stos ::」,當pop在範圍內時(我的意思是說友誼的代碼在class stos裏面,所以我認爲我不應該不使用範圍操作符)。 – groosik

+0

@groosik http://stackoverflow.com/q/8207633/3093378引用接受的答案:*當您在類中聲明帶有非限定標識的朋友函數時,它會在最近的封閉名稱空間作用域中命名函數*密鑰這裏的詞是* namaspace *,所以'friend'不在* scope *上運算符。您需要範圍解析運算符!嘗試刪除'stos ::'[here](http://ideone.com/m672nB),代碼將不再編譯。 – vsoftco

+0

簡單地說'friend stos :: pop()'是類'stos'的方法。而'friend pop()'則引用全局函數。 – GameDeveloper