可以转换C#get,将代码设置为C++

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)

  • 在后一种情况下,标准命名约定似乎是getter的"T temp()"和setter的`void temp(T value)`. (3认同)

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)

  • +1,这既邪恶又聪明:) (2认同)
  • 哦,你可以摆脱开销,*和*有一个工作`operator =`,简单地放弃`.`语法.使用`static TestProperty text;`将名称引入全局范围,并对`operator ^'进行适当的覆盖,并且可以使`a ^ text ="blah"`工作,运行时开销为零.要添加到C#ness,`Test*a; a ^ text`和`test a; 一个^ text`都可以做同样的事情:为什么在语句*将它放在那里时存储`Test`对象*,我们需要做的就是一些表达式模板mojo来抓住它并使用它! (2认同)