- 论坛徽章:
- 0
|
构造函数?
原帖由 "playmud" 发表:
我不这么认为,构造函数和析构函数只是语义上的东西,实际上没有必要的话编译器根本不给你生成.
我对构造函数的认识主要来自于《Thinking in C++>;这本书,
http://www.gcek.net/ref/books/sw/cpp/ticppv1/chapter06.asp
下面是我摘录的部分内容:
The default constructor is so important that if (and only if) there are no constructors for a structure (struct or class), the compiler will automatically create one for you. So this works:
//: C06:AutoDefaultConstructor.cpp
// Automatically-generated default constructor
class V {
int i; // private
}; // No constructor
int main() {
V v, v2[10];
} ///:~
If any constructors are defined, however, and there’s no default constructor, the instances of V above will generate compile-time errors.
You might think that the compiler-synthesized constructor should do some intelligent initialization, like setting all the memory for the object to zero. But it doesn’t – that would add extra overhead but be out of the programmer’s control. If you want the memory to be initialized to zero, you must do it yourself by writing the default constructor explicitly.
Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You should treat this feature as a safety net, but use it sparingly. In general, you should define your constructors explicitly and not allow the compiler to do it for you.
如果你的说法成立,那么书上说的应该是错误的啦,是吗? |
|