我有一个问题,如果我有一个模板类,它又有一个模板方法,它接受该类的另一个实例的参数(具有不同的模板参数),它不能访问被传递的类的受保护或私有成员一个参数,例如:
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.jb51.cc/c/113064.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。