引用运算符不重载

问题描述 投票:1回答:1

我已经定义了一个重载解引用运算符。但是,当我尝试使用->时,我希望调用重载解引用运算符,并将指向特定对象的指针返回给我。之后,我要访问此对象的类的成员。但是,当我使用->时,似乎不会调用重载运算符。需要显式调用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;
}
c++ operator-keyword dereference
1个回答
0
投票
对于您的问题,q.request不应该是指针。例如

template<typename T> class ReqData { public: GenericRequest<T> request; };

那么您可以

(q.request)->getRequest();

LIVE

© www.soinside.com 2019 - 2024. All rights reserved.