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
내가 템플릿 특수화를 사용하여 친구 클래스를하지 않고이 문제를 해결하려면. 내가 아는 한 당신은 생성자를 친구로 선언 할 수 없습니다. 어떤 아이디어?
편집 : 의미에 대한 수정을했습니다. 그래서 내가 생성하려고하는 생성자는 실제로 변환 생성자입니다.
편집 2 : 프로그램을 수정했습니다. 당신이 알아야 할
@chris 아니요 작동하지 않습니다. – gibraltar
참조하십시오 : http://stackoverflow.com/questions/1599171/c-class-member-access-problem-with-templates/ – kennytm
왜'width'와'height'는 type 대신'int' 유형으로 선언됩니다 'T'? – cdhowie