【发布时间】:2012-06-12 17:12:44
【问题描述】:
我有一个带有转换构造函数的模板类 Rect,它允许在 Rect 到 Rect 之间进行转换,反之亦然。但是在编译代码时,编译器会给出一个错误,指出构造函数无法访问类的受保护成员。 这是代码:
#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
我想在不使用模板专业化和结交朋友类的情况下解决这个问题。据我所知,您不能将构造函数声明为朋友。有什么想法吗?
编辑:我已对语义进行了更正。所以我正在尝试构建的构造函数实际上是一个转换构造函数。
Edit2:更正了程序。
【问题讨论】:
-
为什么
width和height被声明为int类型而不是T类型? -
@cdhowie 是的。感谢您指出错误。
标签: c++ templates constructor