I have the following code in C#:
public string Temp
{
get { return sTemp; }
set {
sTemp = value;
this.ComputeTemp();
}
}
Is it possible to convert this and use the get and set this way? I know that you cannot declare like so and I need the ":" to declare but when I try to do this:
public:
std::string Temp
{
get { return sTemp; }
set {
sTemp = value;
this.ComputeTemp();
}
The error I receive is on the first "{" stating expected a ';'
. Any suggestions on how to fix it?
Are you using C++/CLI? If so this is the property syntax
public:
property std::string Temp {
std::string get() { return sTemp; }
void set(std::string value) { sTemp = value; this->ComputeTemp(); }
}
If you are trying to use normal C++ then you are out of luck. There is no equivalent feature for normal C++ code. You will need to resort to getter and setter methods
public:
std::string GetTemp() const { return sTemp; }
void SetTemp(const std::string& value) {
sTemp = value;
this->ComputeTemp();
}
To copy paste one of my answers from a similar question:
WARNING: This is a tongue-in-cheek response and is terrible!!!
Yes, it's sort of possible :)
template<typename T>
class Property
{
private:
T& _value;
public:
Property(T& value) : _value(value)
{
} // eo ctor
Property<T>& operator = (const T& val)
{
_value = val;
return(*this);
}; // eo -
operator const T&() const
{
return(_value);
}; // eo ()
};
Then declare your class, declaring properties for your members:
class Test
{
private:
std::string m_Test;
public:
Test() : text(m_Test)
{
};
Property<std::string> text;
};
And call C# style!
Test a;
a.text = "blah";
std::string content = a.text;
In Visual C++ you can use __declspec(property)
, like this:
public:
__declspec(property(get=get_Temp, put=set_Temp)) std::string Temp;
const std::string& get_Temp { return sTemp; }
void set_Temp(std::string value) {
sTemp = std::move(value);
this->ComputeTemp();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.