C类成员访问问题与模板

前端之家收集整理的这篇文章主要介绍了C类成员访问问题与模板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个问题,如果我有一个模板类,它又有一个模板方法,它接受该类的另一个实例的参数(具有不同的模板参数),它不能访问被传递的类的受保护或私有成员一个参数,例如:
template<typename T>class MyClass
{
    T v;
public:
    MyClass(T v):v(v){}

    template<typename T2>void foo(MyClass<T2> obj)
    {
        std::cout << v     << " ";
        //error C2248: 'MyClass<T>::v' : cannot access private member declared in class 'MyClass<T>'
        std::cout << obj.v << " ";
        std::cout << v + obj.v << std::endl;
    }
};
int main()
{
    MyClass<int> x(5);
    MyClass<double> y(12.3);
    x.foo(y);
}

有没有可以说MyClass< T>中的方法有完全访问MyClass< SomeOtherT>?

解决方法

它们是不同的类型:模板从模板构建新类型.

你必须对你的班级朋友做其他的例子:

template <typename T>class MyClass
{
    T v;
public:
    MyClass(T v):v(v){}

    template<typename T2>void foo(MyClass<T2> obj)
    {
        std::cout << v     << " ";
        std::cout << obj.v << " ";
        std::cout << v + obj.v << std::endl;
    }

    // Any other type of MyClass is a friend.
    template <typename U>
    friend class MyClass;

    // You can also specialize the above:
    friend class MyClass<int>; // only if this is a MyClass<int> will the
                               // other class let us access its privates
                               // (that is,when you try to access v in another
                               // object,only if you are a MyClass<int> will
                               // this friend apply)
};
原文链接:https://www.f2er.com/c/113064.html

猜你在找的C&C++相关文章