取消引用运算符不能重载
Dereference operator is not be overloaded
我定义了一个重载解引用运算符。但是,当我尝试使用->时,我希望重载解引用操作符被调用,并返回指向特定对象的指针。之后,我想访问这个对象的类的成员。然而,当我使用->时,似乎不会调用重载运算符。需要显式调用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)->getRequest();
通向UB。因为q.request
是一个指针,并且被初始化为空指针。
对于您的问题,q.request
不应该是指针。例如
template<typename T>
class ReqData
{
public:
GenericRequest<T> request;
};
然后你可以
(q.request)->getRequest();
实时
相关文章:
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 取消引用运算符不能重载
- 不能将重载比较运算符与 Catch 测试一起使用
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 为什么我不能用两个参数重载 C++ 运算符 []?
- ostream_iterator运算符=在pair<int,int>上失败,但在包装器类上工作。我不能为成对<>重载运算符<<吗?
- 派生类不能用另一个基类的成员重载基类中的私有成员
- 为什么我不能重载运算符<< 与 ostream 和 map( 或 unordered_map)?
- 不能在友元函数中使用重载运算符
- 为什么我不能重载我传递给 std::upper_bound 的比较器
- 不允许使用类型名称,(不能使用重载)
- 在 c++ 中,为什么我们可以重载"运算符 ->"而不能重载"运算符"。
- 不能为我自己的类重载运算符<<
- 不能只删除方法的常量重载?
- 为什么 decltype 不能使用重载函数?
- 不能重载 = 使对象 1 = 0;
- 运算符重载:不能添加两个指针
- 为什么操作符重载不能正常执行
- std::set的操作符重载不能正常工作
- 为什么运算符重载不能正常工作