use*_*497 21 c# c++ visual-studio-2010 visual-c++
我在C#中有以下代码:
public string Temp
{
get { return sTemp; }
set {
sTemp = value;
this.ComputeTemp();
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以转换它并使用get和set这种方式?我知道你不能这样声明我需要":"来声明但是当我尝试这样做时:
public:
std::string Temp
{
get { return sTemp; }
set {
sTemp = value;
this.ComputeTemp();
}
Run Code Online (Sandbox Code Playgroud)
我收到的错误是在第一个"{"说明expected a ';'
.有关如何解决它的任何建议?
Jar*_*Par 38
你在使用C++/CLI吗?如果是这样,这是属性语法
public:
property std::string Temp {
std::string get() { return sTemp; }
void set(std::string value) { sTemp = value; this->ComputeTemp(); }
}
Run Code Online (Sandbox Code Playgroud)
如果您尝试使用普通的C++,那么您就不走运了.普通C++代码没有等效功能.您将需要使用getter和setter方法
public:
std::string GetTemp() const { return sTemp; }
void SetTemp(const std::string& value) {
sTemp = value;
this->ComputeTemp();
}
Run Code Online (Sandbox Code Playgroud)
Moo*_*ice 11
要复制粘贴我的一个答案来自类似的问题:
警告:这是一个诙谐的反应,很糟糕!
是的,这有点可能:)
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 ()
};
Run Code Online (Sandbox Code Playgroud)
然后声明您的类,为您的成员声明属性:
class Test
{
private:
std::string m_Test;
public:
Test() : text(m_Test)
{
};
Property<std::string> text;
};
Run Code Online (Sandbox Code Playgroud)
并调用C#风格!
Test a;
a.text = "blah";
std::string content = a.text;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3349 次 |
最近记录: |