我想在类内部设置类的成员变量的值,而不使用 setter 。
我的代码:
class MyWindowSettings {
public:
const ofGLFWWindowSettings& get(){
return settings;
}
int numSamples;
bool resizable;
private:
ofGLFWWindowSettings settings;
};
ofGLFWWindowSettings
还具有以下公共(public)成员变量:int numSamples;
bool resizable;
而且我希望能够不使用 setter 而设置这些变量的值。
我希望能够..例如,
MyWindowSettings settings;
settings.numSamples = 8;
settings.resizable = true;
然后应立即将内部
ofGLFWWindowSettings
的numSamples
和resizable
设置为这些值。是否有任何可能的解决方案可以在不使用setter或不继承
ofGLFWWindowSettings
的情况下实现这一目标? 最佳答案
是的,有两个选项,它们与您喜欢的语法有不同的相似性。
选项1-成员引用
class MyWindowSettings {
public:
MyWindowSettings()
: numSamples(settings.numSamples),
resizable(settings.resizable)
{}
~MyWindowSettings() = default;
MyWindowSettings(const MyWindowSettings & other)
: settings(other.settings),
numSamples(settings.numSamples),
resizable(settings.resizable)
{}
MyWindowSettings& operator=(const MyWindowSettings & other)
{
settings = other.settings;
return *this;
}
MyWindowSettings(MyWindowSettings && other)
: settings(std::move(other.settings)),
numSamples(settings.numSamples),
resizable(settings.resizable)
{}
MyWindowSettings& operator=(MyWindowSettings && other)
{
settings = std::move(other.settings);
return *this;
}
const ofGLFWWindowSettings& get(){
return settings;
}
int & numSamples;
bool & resizable;
private:
ofGLFWWindowSettings settings;
};
优点:
缺点:
选项2-公开
ofGLFWWindowSettings
class MyWindowSettings {
public:
ofGLFWWindowSettings settings;
};
优点:
ofGLFWWindowSettings
的 setter/getter 缺点:
我个人比较喜欢这种情况,假设还没有显示
MyWindowSettings
的其他成员。MyWindowSettings settings;
settings.settings.numSamples = 8;
settings.settings.resizable = true;
选项3-无
MyWindowSettings
只需直接使用
ofGLFWWindowSettings
即可选项3.a-别名定义
using MyWindowSettings = ofGLFWWindowSettings;