我已经在C#中编程了一段时间,现在我想要提高我的C++技能.
上课:
class Foo
{
const std::string& name_;
...
};
Run Code Online (Sandbox Code Playgroud)
什么是最好的方法(我只想允许对name_字段的读访问):
inline const std::string& name() const { return name_; }
谢谢.
我原来是来自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) (暂不回答你应该拥有它们的问题.)
我一直希望只使用函数重载为getter和setter提供相同的名称.
int rate() { return _rate; }
void rate(int value) { _rate = value; }
// instead of
int getRate() { return _rate; }
void setRate(int value) { _rate = value; }
// mainly because it allows me to write the much cleaner
total( period() * rate() );
// instead of
setTotal( getPeriod() * getRate() );
Run Code Online (Sandbox Code Playgroud)
当然我是对的,但我想知道图书馆作家是否有任何理由?
我无法将单一责任原则与封装协调一致.似乎在类之间分配责任需要暴露大量数据.举个例子,考虑一些叫做的对象DataPoints
.DataPoints
其中包括x和y坐标.我可以创建一个填充的Generator类DataPoints
.现在,假设我想绘制这些数据点.显然,这是一个单独的责任,可能来自一个叫做的类DataPointsPlotter
.但是为了绘制数据,我需要知道内部x和y坐标是什么.只需一个处理两个类,这没问题.x和y是内部变量,但create()和print()方法都可以访问这些变量.我可以暴露x和y(也许是通过getter/setters - 呃)或者我可以通过DataPoints
Plotter类的结构,但它仍然需要进入x和y.我可以在DataPoints
我发送x和y 的类中声明一个Plotter实例.但这仍然是曝光.
在这个例子中,如何使用绘图仪绘制x和y而不违反封装?
language-agnostic encapsulation single-responsibility-principle