简体   繁体   中英

Why am I getting the error 'cannot access private member declared in class' even though I have declared friend class

Consider the following code:

#include <iostream>

template<typename T>
class A
{
    private:
        T value;

    public:
        A(T v){ value = v;}

        friend class A<int>;
};

template<typename T>
class B
{
    public:
        T method(A<T> a){ return a.value; }  // problem here, but why?
};

int main()
{
    A<int> a(2);
    B<int> b;

    std::cout << b.method(a) << std::endl;
}

Why do I still get the error: "'A::value': cannot access private member declared in class 'A'" even though I have declared A as a friend class for the template type int?

Edit Note that moving the friend class line inside B also does not work:

template<typename T>
class A
{
    private:
        T value;

    public:
        A(T v){ value = v; }
};

template<typename T>
class B
{
    public:
    T method(A<T> a){ return a.value; }

    friend class A<int>;
};
template<typename T>
class B;

template<typename T>
class A
{
    private:
        T value;
    public:
        A(T v){ value = v;}
        friend class B<int>;
};

template<typename T>
class B
{
    public:
        T method(A<T> a){ return a.value; }
};

The class A should have class B as a friend, if you want B to use A's private attributes.

#include <iostream>

template<typename T>
class A
{
    private:
        T value;

    public:
        A(T v){ value = v;}
        T getValue() { return value; }


};

template<typename T>
class B
{
    public:
        friend class A<int>;
        T method(A<T> a){ return a.getValue(); } 

};

int main()
{
    A<int> a(2);
    B<int> b;

    std::cout << b.method(a) << std::endl;
}

Few changes. a.value() value is a private member variable, so we created a getter below getValue() and replaced where needed. Also moved friend class A to class B.

T method(A<T> a){ return a.value; }

problem here, but why?

Because class B is accessing class A 's private member value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM