加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C类成员访问问题与模板

发布时间:2020-12-16 06:01:13 所属栏目:百科 来源:网络整理
导读:我有一个问题,如果我有一个模板类,它又有一个模板方法,它接受该类的另一个实例的参数(具有不同的模板参数),它不能访问被传递的类的受保护或私有成员一个参数,例如: templatetypename Tclass MyClass{ T v;public: MyClass(T v):v(v){} templatetypename T2v
我有一个问题,如果我有一个模板类,它又有一个模板方法,它接受该类的另一个实例的参数(具有不同的模板参数),它不能访问被传递的类的受保护或私有成员一个参数,例如:
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)
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读