Код: Выделить всё
// myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include
class MyClass {
public:
MyClass(int number);
MyClass(const MyClass& other);
MyClass& operator=(MyClass rhs);
~MyClass();
int getNumber();
void setNumber(int number);
struct Impl;
private:
std::unique_ptr pimpl;
Impl* operator->();
};
#endif // MYCLASS_H
Код: Выделить всё
// myclass.cpp
#include "myclass.h"
struct MyClass::Impl {
Impl(int number) : m_data{ number } {}
int m_data;
};
MyClass::MyClass(int number) : pimpl{ new Impl(number) } {}
MyClass::MyClass(const MyClass& other) : pimpl{ new Impl(*other.pimpl) } {}
MyClass& MyClass::operator=(MyClass rhs) {
std::swap(pimpl, rhs.pimpl);
return *this;
}
MyClass::~MyClass() = default;
MyClass::Impl* MyClass::operator->()
{
return pimpl.get();
}
int MyClass::getNumber() {
return pimpl->m_data;
}
void MyClass::setNumber(int number) {
pimpl->m_data = number;
}
Код: Выделить всё
#include "myclass.h"
#include
int main()
{
MyClass obj1{ 10 };
MyClass obj2{ 200 };
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/78708432/how-to-implement-an-overloaded-arrow-operator-for-a-pimpl-implementation[/url]
Мобильная версия