我想要我的默认值!
不,当前的 C++ 中没有“直接”的方式来为内置值提供这种“默认”行为。
正如在其他两个问题中已经回答的那样,您需要在 MyClass 的每个构造函数中提供值。
但我真的需要它!!!
但如果您真的需要它,有一种间接获得它的方法:将内置类型包装在模板化类中,重载其支持的运算符。
这样你就可以写出如下代码了:
void foo()
{
bool b ; // WRONG : Not initialized
Variable<bool> bb ; // Ok : Initialized to false
int i ; // WRONG : Not initialized
Variable<int> ii ; // Ok : Initialized to 0
// etc.
}
所需的代码例如为 bool :
template<typename T>
class Variable
{
T value_ ;
public :
Variable() ;
Variable(const T & rhs) ;
Variable(const Variable & rhs) ;
Variable & operator = (const T & rhs) ;
Variable & operator = (const Variable & rhs) ;
operator T() const ;
// define all other desired operators here
} ;
然后,对方法进行编码以获得所需的行为。例如:
template<typename T>
inline Variable<T>::Variable()
: value_(0)
{
}
// For the fun, I want all booleans initialized to true !
template<>
inline Variable<bool>::Variable()
: value_(true)
{
}
// For the fun, I want all doubles initialized to PI !
template<>
inline Variable<double>::Variable()
: value_(3.1415)
{
}
// etc.
template<typename T>
inline Variable<T>::operator T() const
{
return value_ ;
}
// etc.
运算符列表可能非常多,具体取决于您要对变量执行的操作。例如,整数将具有所有算术运算符。并且所有运算符都不可重载(在这种情况下也不应该如此),因此您不会拥有所有内置行为。
无论如何,如您所见,如果需要特定行为,您可以为某些类型专门化方法。
完成方法列表并正确编码是一个非常好的 C++ 练习。
完成后,您只需声明变量:
class MyClass
{
Q_OBJECT
public:
MyClass();
~MyClass();
Variable<bool> myBool ; // it will be set to false, as defined
Variable<int> myInt ; // it will be set to 0, as defined
};
然后,您将按如下方式使用它:
void foo()
{
MyObject o ;
o.myBool = true ;
if(o.myInt == 0)
{
++o.myInt ;
}
}
确保包装类的所有代码都内联并包含在包含的头文件中,并且在使用“发布”选项编译时不会产生性能成本。