LINUX.ORG.RU

История изменений

Исправление evilface, (текущая версия) :

Вот так как-то.

#include <iostream>


template <typename T>
class Property {
private:
    Property & operator=(const Property &) = delete;
    Property(const Property &) = delete;
    Property() = delete;
protected:
    T value;
public:
    explicit Property(const T &value) {
        this->value = value;
    }

    const T& operator=(const T &value) {
        set(value);
        return this->value;
    }

    operator T() const {
        return get();
    }

    virtual void set(const T &value) {
        this->value = value;
    }

    virtual T get() const {
        return value;
    }
};

template <typename T>
std::ostream& operator<<(std::ostream &os, const Property<T> &prop) {
    os << static_cast<T>(prop);
    return os;
}

template <typename T>
std::istream& operator>>(std::istream &is, Property<T> &prop) {
    T val;
    is >> val;
    prop = val;
    return is;
}


class A {
public:
    class Val : public Property<int> {
    public:
        Val() : Property(0) {}

        void set(const int &value) {
            this->value = 2*value;
        }

        int get() const {
            return this->value;
        }
    } val;
};


int main() {
    A obj;
    std::cin >> obj.val;
    std::cout << obj.val;

    return 0;
}

Введём 10 — выведет 20.

Исходная версия evilface, :

Вот так как-то.

#include <iostream>


template <typename T>
class Property {
private:
    Property & operator=(const Property &) = delete;
    Property(const Property &) = delete;
    Property() = delete;
protected:
    T value;
public:
    explicit Property(const T &value) {
        this->value = value;
    }

    const T& operator=(const T &value) {
        set(value);
        return this->value;
    }

    operator T() const {
        return get();
    }

    virtual void set(const T &value) {
        std::cout << "prop.set";
        this->value = value;
    }

    virtual T get() const {
        return value;
    }
};

template <typename T>
std::ostream& operator<<(std::ostream &os, const Property<T> &prop) {
    os << static_cast<T>(prop);
    return os;
}

template <typename T>
std::istream& operator>>(std::istream &is, Property<T> &prop) {
    T val;
    is >> val;
    prop = val;
    return is;
}


class A {
public:
    class Val : public Property<int> {
    public:
        Val() : Property(0) {}

        void set(const int &value) {
            this->value = 2*value;
        }

        int get() const {
            return this->value;
        }
    } val;
};


int main() {
    A obj;
    std::cin >> obj.val;
    std::cout << obj.val;

    return 0;
}

Введём 10 — выведет 20.