i have seen several codes for do properties and some need more work to build them, so i came up with my own code:
Code:
#include <iostream>
#include <functional>
using namespace std;
template <typename T>
class property
{
private:
T PropertyValue;
std::function<void(void)> getf;
std::function<void(T a)> setf;
public:
property()
{
//nothing
};
property(T value)
{
PropertyValue=value;
};
property(std::function<void(void)> GetFunction,std::function<T(void)> SetFunction)
{
setf=SetFunction;
getf=GetFunction;
}
property& operator=(T value)
{
if(setf==NULL)
PropertyValue=value;
else
setf(value);
return *this;
}
T& operator=(property value)
{
if(getf==NULL)
return PropertyValue;
else
return getf();
}
friend ostream& operator<<(ostream& os, const property& dt)
{
os << dt.PropertyValue;
return os;
}
friend istream& operator>>(istream &input,property &dt)
{
input >> dt.PropertyValue;
return input;
}
};
class test
{
public:
test()
{
//nothing
}
property<string> Name;
property<int> Age;
};
test a;
int main()
{
a.Name="joaquim " "Miguel";
a.Age=10+15;
cout << a.Age << endl;
cout << "What is your age?\n";
cin >> a.Age;
cout << "your age is: " << a.Age << endl;
return 0;
}
these code works fine and no errors, but when i choose the get and set functions, i get several errors
Code:
#include <iostream>
#include <functional>
using namespace std;
template <typename T>
class property
{
private:
T PropertyValue;
std::function<void(void)> getf;
std::function<void(T a)> setf;
public:
property()
{
//nothing
};
property(T value)
{
PropertyValue=value;
};
property(std::function<void(void)> GetFunction,std::function<T(void)> SetFunction)
{
setf=SetFunction;
getf=GetFunction;
}
property& operator=(T value)
{
if(setf==NULL)
PropertyValue=value;
else
setf(value);
return *this;
}
T& operator=(property value)
{
if(getf==NULL)
return PropertyValue;
else
return getf();
}
friend ostream& operator<<(ostream& os, const property& dt)
{
os << dt.PropertyValue;
return os;
}
friend istream& operator>>(istream &input,property &dt)
{
input >> dt.PropertyValue;
return input;
}
};
class test
{
private:
int age;
int getage()
{
return age;
}
void setage(int value)
{
age=value;
}
public:
test()
{
//nothing
}
property<string> Name;
property<int> Age(&getage,&setage);
};
test a;
int main()
{
a.Name="joaquim " "Miguel";
a.Age=10+15;
cout << a.Age << endl;
cout << "what is your age?\n";
cin >> a.Age;
cout << "your age is: " << a.Age << endl;
return 0;
}
now i get several errors like:
- error: expected identifier before '&' token;
- error: invalid use of member function (did you forget the '()' ?);
- error: no match for 'operator<<' (operand types are 'std:stream {aka std::basic_ostream<char>}' and '<unresolved overloaded function type>')|
(and more warnings and errors)
(i belive that i know why these last error is when i overload the << and >> operators)
can anyone advice me, please?