我想在不使用setter的情况下在类中设置类的成员变量的值. 我的代码: class MyWindowSettings {public: const ofGLFWWindowSettings get(){ return settings; } int numSamples; bool resizable;private: ofGLFWWindowSettings s
我的代码:
class MyWindowSettings { public: const ofGLFWWindowSettings& get(){ return settings; } int numSamples; bool resizable; private: ofGLFWWindowSettings settings; };
ofGLFWWindowSettings也有公共成员变量
int numSamples; bool resizable;
我希望能够在不使用setter的情况下设置这些变量的值.
我希望能够..例如,
MyWindowSettings settings; settings.numSamples = 8; settings.resizable = true;
然后,应立即将GLFWWindowSettings的numSamples和resizable的内部设置为这些值.
有没有可能的解决方案来实现这一点,而不使用setter或继承GLFWWindowSettings?
是的,有几个选项,与您喜欢的语法具有不同的相似性.选项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 – 公开GLFWWindowSettings
class MyWindowSettings { public: ofGLFWWindowSettings settings; };
优点:
>非常简洁
>你也不需要forGLFWWindowSettings的getter
缺点:
>语法不完全相同
我个人更喜欢这个,假设MyWindowSettings的其他成员没有显示.
MyWindowSettings settings; settings.settings.numSamples = 8; settings.settings.resizable = true;
选项3 – 没有MyWindowSettings
只需直接使用GLFWWindowSettings即可
选项3.a – 别名定义
using MyWindowSettings = ofGLFWWindowSettings;