关于重载operator->有几点需要特别的注意:
1, 重载operator->()括号里面是不能有参数的.
2, 重载operator->他只能是非静态的成员函数.
3,重载的operator->如果返回的是一个指针: T* operator->()这种形式, 那么就将 运算符的右操作数 当作这个原始指针所指向类型的成员进行访问 .
4,重载的operator->如果返回的是一个非指针类型: T operator->()/T& operator->() 这种形式,那么将接着调用T的operator->直到返回类型为一个指针为止.
#include <iostream>
#include <iterator>
#include <forward_list>
#include <vector>
#include <string>
#include <algorithm>
#include <memory>
class Item {
public:
int value;
Item() = default;
Item(const int& _value) :value(_value) {}
Item(const Item& other) :value(other.value) {}
Item(Item&& other) :value(std::move(other.value)) {}
~Item() = default;
Item& operator=(const Item& other)
{
this->value = other.value;
return *this;
}
Item& operator=(Item&& other)
{
this->value = std::move(other.value);
return *this;
}
void print()
{
std::cout << (this->value) << std::endl;
}
};
class Inner {
public:
Item* item;
Inner(const int& value) :item(new Item(value)) {}
Inner(Inner&& other) :item(std::move(other.item)) { other.item = nullptr; }
Inner(const Inner& other) = delete;
Inner& operator=(const Inner& other) = delete;
Inner& operator=(Inner&& other)
{
this->item = std::move(other.item);
other.item = nullptr;
return *this;
}
~Inner()
{
if (this->item != nullptr) {
delete (this->item);
}
}
Item* operator->()
{
std::cout << "Inner::operator->" << std::endl;
return (this->item);
}
};
class Wrapper {
private:
Inner* inner;
public:
Wrapper(const int& value_) :inner(new Inner(value_)) {}
Wrapper() = default;
Wrapper(const Wrapper&) = delete;
Wrapper& operator=(const Wrapper&) = delete;
~Wrapper()
{
if (this -> inner != nullptr) {
delete (this->inner);
}
}
void printf()
{
std::cout << "test" << std::endl;
}
Inner& operator->()
{
std::cout << "Wrapper::operator->" << std::endl;
return *(this->inner);
}
};
class Wrap {
private:
Item* item;
public:
Wrap(const int& value) :item(new Item(value)) {}
Wrap(const Wrap&) = delete;
Wrap(Wrap&& other) :item(std::move(other.item)) {}
Wrap& operator=(const Wrap&) = delete;
Wrap& operator=(Wrap&& other)
{
this->item = std::move(other.item);
other.item = nullptr;
return *this;
}
Item* operator->()
{
return (this->item);
}
void print()
{
std::cout << "test" << std::endl;
}
};
int main()
{
//case 1:
Wrapper* w = new Wrapper(20);
w->printf();
//case 2:
Wrapper wTwo(30);
wTwo->print();
//case 3:
Wrap* p = new Wrap(40);
p->print();
//case 4:
Wrap wrap(50);
wrap->print();
delete w;
delete p;
return 0;
}