我原来是来自C#的世界,我正在学习C++.我一直想知道在C++中获取和设置函数.在C#中,这些使用非常流行,而像Visual Studio这样的工具通过使它们变得非常容易和快速实现来促进使用.但是,在C++世界中似乎并非如此.
这是C#2.0代码:
public class Foo
{
private string bar;
public string Bar
{
get { return bar; }
set { bar = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
或者,在C#3.0中:
public class Foo { get; set; }
Run Code Online (Sandbox Code Playgroud)
可能人们会说,那是什么意思呢?为什么不创建一个公共字段,然后在需要时将其变为属性; 老实说,我其实不确定.我只是出于好的做法,因为我已经看过很多次了.
现在因为我已经习惯了这样做,我觉得我应该把习惯延续到我的C++代码中,但这真的有必要吗?我没有像C#那样频繁地完成它.
无论如何,这是我收集的C++:
class Foo
{
public:
std::string GetBar() const; // Thanks for the tip Earwicker.
void SetBar(std::string bar);
private:
std::string bar;
}
const std::string Foo::GetBar()
{
return bar;
}
void Foo::SetBar(std::string bar)
{
// Also, I always wonder if using 'this->' is good …Run Code Online (Sandbox Code Playgroud)