模板转换构造函数无法访问受保护的数据成员 [英] templated conversion constructor fails to access protected data members
问题描述
我有一个模板类Rect与转换构造函数,允许在Rect到Rect之间转换,反之亦然。但是当编译代码时,编译器给出一个错误,说明构造函数不能访问类的受保护成员。
这里是代码:
I have a templated class Rect with conversion constructor which allows conversion between Rect to Rect and vice a versa. But when compiling the code, the compiler gives an error stating the constructor can't access the protected members of the class. Here is code:
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
template< typename T >
class Rect{
protected:
T width, height;
public:
Rect(T a, T b){
width = a;
height = b;
}
template< typename U >
Rect(Rect<U> const &r){
width = r.width;
height = r.height;
}
int area(){
return width*height;
}
};
int main(){
Rect<int> a(3,4);
Rect<float> b(a);
cout<<b.area()<<endl;
}
这里是编译错误:
test.cpp: In constructor ‘Rect<T>::Rect(const Rect<U>&) [with U = int, T = float]’:
test.cpp:28:18: instantiated from here
test.cpp:10:7: error: ‘int Rect<int>::width’ is protected
test.cpp:18:5: error: within this context
test.cpp:10:14: error: ‘int Rect<int>::height’ is protected
test.cpp:19:5: error: within this context
我想解决这个问题,而不使用模板专门化和做朋友类。据我所知,你不能将构造函数声明为朋友。任何想法?
I want to solve this problem without using template specialization and making friend classes. As far as I know you can't declare constructors as friends. Any ideas?
编辑:我已对语义进行更正。因此,我想要构建的构造函数实际上是一个转换构造函数。
I have made corrections to semantics. So the constructor I am trying to build is really a conversion constructor.
Edit2:更正了程序。
推荐答案
正如K-ballo所说, Rect< int>
和 Rect< float> ;
是不同的类型,并且不能访问彼此的私有和受保护成员。您可以通过向您的课程添加以下模板朋友声明(如此)来明确允许此操作:
As K-ballo mentioned, Rect<int>
and Rect<float>
are different types, and do not have access to each others' private and protected members. You can explicitly allow this by adding the following template friend declaration to your class (like so):
template <typename U> friend class Rect;
语义上,这意味着对于任何类型 U
,给予类 Rect< U>
访问我的私有和受保护的成员 - 它是每个 Rect
实例化到每个其他 Rect
实例化。
Semantically, this means "for any type U
, give the class Rect<U>
access to my private and protected members" -- it is an outgoing permission grant from every Rect
instantiation to every other Rect
instantiation.
请注意,访问器 width
和 height
(如K-ballo建议) - 那么你可以在转换中使用这些访问器构造函数并完全放弃了朋友的定义。我宁愿他的解决方案在我的;我给我的只是另一个可能的选择,并向你介绍一个你可能不熟悉的概念(朋友,特别是模板朋友)。
Note that this won't be necessary if you add accessors for width
and height
(as K-ballo suggests) -- then you can just use those accessors in the conversion constructor and forgo the friend definition entirely. I would prefer his solution over mine; I give mine merely as another possible option and to introduce to you a concept (friends, and specifically template friends) that you might not be familiar with.
这篇关于模板转换构造函数无法访问受保护的数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!