问题描述
如果至少有一个用户定义的构造函数,则没有构造函数隐式声明为
。
struct my_vec:public vector< int> {
double foo;
my_vec(size_t n):vector< int>(2 * n){}
// oops,no默认ctor更多
//现在必须做很多愚蠢的打字,例如:
my_vec():vector< int>(){}
//等
};
有没有其他人觉得这种行为很烦人?相反,我宁愿
编译器隐式声明用户声明的所有构造函数都不是
。
If there is at least one user-defined constructor, no constructors are
implicitly declared.
struct my_vec : public vector<int> {
double foo;
my_vec(size_t n) : vector<int>(2*n) {}
// oops, no default ctor any more
// have to do a lot of stupid typing now , like:
my_vec() : vector<int>() {}
// etc.
};
Does anyone else find this behavior annoying? Instead, I would prefer
for the compiler to implicitly declare all constructors that are not
declared by the user.
推荐答案
我个人不希望没有构造函数是隐式定义的。但是我认为规则背后的目的是确定最小的
隐式构造函数将与C保持兼容。
例如这段代码必须编译为C和C ++。
// C代码
typedef struct
{
int x;
} X;
X x; //使用隐式默认构造函数
X y = x; //使用隐式拷贝构造函数
一旦你定义了一个构造函数,你就不再与C
兼容了,所以规则可以收紧。
john
Personally I would prefer no constructors to be implicitly defined. But I
think the purpose behind the rules as they are is to define the minimum
implicit constructors will remaining compatible with C.
E.g. this code has to compile as C and C++.
// C code
typedef struct
{
int x;
} X;
X x; // use of implicit default constructor
X y = x; // use of implicit copy constructor
As soon as you define one constructor, you are no longer compatible with C
anyway, so the rules can be tightened.
john
其实你不喜欢不得不这样做
my_vec(){}
足够好,没有太多按键。甚至这个
my_vec(size_t n = 0):vector< int>(2 * n){}
并且不要''公开继承STL容器类,其形式不好。
john
Actually you don''t have to do that
my_vec() {}
is good enough, no too many keystrokes. Or even this
my_vec(size_t n = 0) : vector<int>(2*n) {}
And don''t publically inherit from STL container classes, its bad form.
john
struct my_vec:public vector< ; INT> {
double foo;
public:
my_vec(std :: vector< int> :: size_type n = 0) //默认ctor
:vector< int>(2 * n){}};
};
BTW为什么你是继承自std :: vector吗?
-Mike
struct my_vec : public vector<int> {
double foo;
public:
my_vec(std::vector<int>::size_type n = 0) // default ctor
: vector<int>(2*n) {} };
};
BTW why are you inheriting from std::vector?
-Mike
这篇关于隐式构造函数声明(用户烦恼)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!