我有一个C类,它有一个成员变量,当没有设置时,每个成员变量都必须设置为默认值。我在C中有很多成员变量,以及设置一些变量而不设置其他变量等的各种构造函数,因此为了确保必须具有默认值的成员变量被设置为默认值,我依赖于void Init()成员函数:在Init中,我将所有具有默认值的成员变量设置为它们的默认值,并在构造函数中调用Init等。
现在,我必须在稍后的代码中引用默认值,通常是为了知道客户端是否通过setter将它们设置为默认值以外的其他值,以便我可以触发一个或另一个行为。
我的问题是:实现“成员变量的默认值”概念的最佳方式是什么?通过在标头中定义的常量声明C?作为const成员变量?作为static const成员变量?
备注:我被允许使用c++ <= 2003。
发布于 2016-10-31 01:01:55
如果您有“各种构造函数”,那么您必须在初始化器列表中的构造函数的代码中添加未初始化的成员变量的初始化。
如果这感觉很麻烦,你可以在一个通用的初始化器函数中将其排除。
现代C++允许构造函数继承,其中一个构造函数可以调用像here这样的(基)构造函数。
发布于 2016-10-31 17:15:25
这是一个在C++03中工作的ideea:
template <class T> struct Default_value
{
private:
T value_;
T default_value_;
public:
Default_value(const T& default_value)
: value_(default_value), default_value_(default_value)
{}
const T& get() const { return value_; }
T& get() { return value_; }
const T& get_default() const { return default_value_; }
bool is_default() const { return value_ == default_value_; }
};
struct X_init {
Default_value<int> a_, b_;
Default_value<std::string> str_;
X_init() : a_(24), b_(42), str_("This is sparta") {}
X_init& set_a(int a) { a_.get() = a; return *this; }
X_init& set_b(int b) { b_.get() = b; return *this; }
X_init& set_str(const std::string& str) { str_.get() = str; return *this; }
};
struct X {
X_init values_;
X() : values_() {}
X(const X_init& values) : values_(values) {}
//... X implementation
};int main()
{
X x = X_init().set_a(32).set_str("nope");
cout << std::boolalpha;
cout << "a: " << x.values_.a_.get() << " " << x.values_.a_.is_default() << endl;
cout << "b: " << x.values_.b_.get() << " " << x.values_.b_.is_default() << endl;
cout << "str: " << x.values_.str_.get() << " " << x.values_.str_.is_default() << endl;
}a: 32 false
b: 42 true
str: nope false你必须做更多的工作,但它做的正是你想要的。
当然,您可以调整和/或扩展它以满足您的需求。
ideea很简单。我们有一个Default_value模板化的类。这允许我们显式设置所需的默认值,并跟踪该值是否从默认值更改。
然后我们有了X_init,一个专门设计用来初始化X成员的类。优点是您可以链接setter,因此您可以显式设置一些成员,而将其余成员保留为默认成员。这就是所谓的named parameter idiom
这种方法的缺点是在一个X_init类中捆绑了X的所有数据成员。如果您不喜欢这样,可以将X_init逻辑合并到X中
struct X {
Default_value<int> a_, b_;
Default_value<std::string> str_;
X() : a_(24), b_(42), str_("This is sparta") {}
X& set_a(int a) { a_.get() = a; return *this; }
X& set_b(int b) { b_.get() = b; return *this; }
X& set_str(const std::string& str) { str_.get() = str; return *this; }
};
int main()
{
X x = X().set_a(32).set_str("nope");
cout << std::boolalpha;
cout << "a: " << x.a_.get() << " " << x.a_.is_default() << endl;
cout << "b: " << x.b_.get() << " " << x.b_.is_default() << endl;
cout << "str: " << x.str_.get() << " " << x.str_.is_default() << endl;
}https://stackoverflow.com/questions/40330504
复制相似问题