我已经定义了一个重载解引用运算符。但是,当我尝试使用->时,我希望调用重载解引用运算符,并将指向特定对象的指针返回给我。之后,我要访问此对象的类的成员。但是,当我使用->时,似乎不会调用重载运算符。需要显式调用olverloading运算符->看看下面的例子
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class GenericRequest
{
public:
GenericRequest()
{
m_request = new T();
}
~GenericRequest()
{
if (m_request)
{
delete m_request;
}
}
T& operator *()
{
return *m_request;
}
T* operator ->()
{
return m_request;
}
private:
T* m_request;
};
class SpecificRequest
{
public:
inline const std::string& getRequest() const {
return m_request;
}
inline void setRequest(const std::string& request) {
m_request = request;
}
private:
std::string m_request;
};
template<typename T>
class ReqData
{
public:
ReqData()
:request(NULL)
{
}
~ReqData()
{
if (NULL != request)
{
delete request;
}
}
GenericRequest<T>* request;
};
int main()
{
ReqData<SpecificRequest> q;
//(q.request)->getRequest();-->This call generates error
q.request->operator->()->getRequest();
return 0;
}
q.request
不应该是指针。例如template<typename T>
class ReqData
{
public:
GenericRequest<T> request;
};
那么您可以
(q.request)->getRequest();