Класс своства:
template<typename T>
class Property
{
private:
T& _value;
public:
Property(T& value):
_value(value){ }
void operator=(const T& value)
{
_value = value;
}
operator T() const
{
return _value;
}
};
Пример класса в котром реализуется свойства:
class Person
{
public:
Property<int> Age = Property<int>(_age);
Property<std::string> Name = Property<std::string>(_name);
private:
int _age;
std::string _name;
public:
Person(int age, const std::string& name) :
_age(age),
_name(name){ }
friend std::ostream& operator<<(std::ostream& os, const Person& person)
{
os << std::format("Name: {}, Age: {}\n", person._name, person._age);
return os;
}
};
int main()
{
auto person = Person(15, "Alex");
// std::cout << person;
std::cout << person.Age << std::endl;
std::cout << person.Name << std::endl; // тут ошибки
}
Ошибки:
1. Error (active) E0349 no operator "<<" matches these operands.
2. Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'Property' (or there is no acceptable conversion).