질문은 마지막 두 줄의 코드에서 제공됩니다. TestClass
더 멤버 함수 Detach
이 없기 때문에 C++ - 왜 operator ->를 사용하여 SmartPtr의 멤버 함수에 액세스해야합니까?
template<class T> // template class for smart
class SmartPtr { // pointers-to-T objects
public:
SmartPtr(T* realPtr = 0);
T* operator->() const;
T& operator*() const;
T* Detach(void)
{
T* pData = pointee;
pointee = NULL;
return pData;
}
private:
T *pointee;
...
};
class TestClass {}
SmartPtr<TestClass> sPtr(new TestClass);
TestClass* ptrA = sPtr->Detach();
// why I always see people use this method to access member functions of a Smart pointer.
// We can use sPtr-> b/c we have defined operator->() in SmartPtr.
TestClass* ptrB = sPtr.Detach();
// Question: Is this a valid C++ way? If not, why?
는