2015-05-22 76 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