내 문제는 간단합니다. 나는 동적으로 할당 된 타입에 대한 포인터를 가지고있는 클래스 템플릿을 가지고있다. 간접 연산자를 오버로드하여 -> 연산자를 사용하여 클래스 템플릿 인스턴스를 참조하면 직접 포함 된 포인터를 사용하는 것처럼 리디렉션됩니다.C에서 간접 연산자를 오버로드
instance.ptr->someMemberMethod();
단순히 입력 : 심지어
intance->someMemberMethod();
MyClass<SomeObject> instance;
그래서 내가 원하는 것은 대신 입력 할 필요하다 :
template<class T>
class MyClass
{
T *ptr;
...
// created dynamic resource for ptr in the constructor
};
어떤 종류의 MyClass에 만들기 너 instance
은 ap가 아니다. ointer 포인터가 마치 instance
에있는 것처럼 작동합니다. 운영자 과부하로 그 격차를 해소하는 방법은 무엇입니까?
template<class T>
class MyClass
{
T* ptr;
public:
T* operator->() {
return ptr;
}
// const version, returns a pointer-to-const instead of just a pointer to
// enforce the idea of the logical constness of this object
const T* operator->() const {
return ptr;
}
T& operator*() {
return *ptr;
}
// const version, returns a const reference instead of just a reference
// to enforce the idea of the logical constness of this object
const T& operator*() const {
return *ptr;
}
};
참고로 인해 언어의 창조자에 의해 디자인 결정, 당신은 .
연산자를 오버로드 할 수 없습니다 :
현대 C + + 디자인 (Andrei Alexandrescu) 당신이 더 깊이 싶으면 피사체에 대한 좋은 정보가 있습니다. –