4

I have 2 classes (firstClass and secondClass) which firstClass is a friend of secondClass, and has a private nested unordered_map, which I want to access it in a function of secondClass. So basically the code is like this:

    class secondClass;
    typedef unordered_map STable<unsigned, unordered_map<unsigned, double> > NESTED_MAP;


        class firstClass{
        friend class secondClass;
        void myfunc1(secondClass* sc){
            sc->myfunc2(&STable);
        }
        private:
            NESTED_MAP STable;
        };


        class secondClass{
        public:
            void myfunc2(NESTED_MAP* st){
            //Here I want to insert some elements in STable.
            //Something like:
            st[1][2]=0.5;
            }
        };
    int main(){
            firstClass  fco;
            secondClass sco;
            fco.myfunc1(&sco);
            return 0;

        }

I know that it should be trivial, but I don't know how to solve it. Any idea? (I changed the code and the question to make it more clear)

4

1 回答 1

6

朋友类可以访问任何私有成员,因此您可以简单地调用方法并修改属性,就像它们是公共的一样。

这里的文档,它说:

友元声明出现在类主体中,并授予函数或其他类访问友元声明出现的类的私有和受保护成员的权限。

也就是说,通过查看您的示例,我宁愿更改放置friend关键字的位置,因为在我看来myfunc2不应该是public

它遵循一个示例,我应用了上述建议,并显示了如何处理来自朋友类的私有成员:

#include<unordered_map>

using namespace std;

class firstClass;

class secondClass{
    friend class firstClass;

private:
    void myfunc2(unordered_map<unsigned,double>& map){
        map[1]=0.5;
    }
};

class firstClass{
public:
void myfunc1(secondClass* sc){
    // here firstClass is accessing a private member
    // of secondClass, for it's allowed to do that
    // being a friend
    sc->myfunc2(STable);
}
private:
    unordered_map<unsigned,double> STable;
};

int main(){
    firstClass  fco;
    secondClass sco;
    fco.myfunc1(&sco);
    return 0;
}
于 2015-11-22T22:30:20.400 回答