关于 Constructor&Destructor
请问Constructor&Destructor是不是必须一一对应的,也就是说没调用一次CON就得调用一次DES,如果是的话,下面的程序哪位给解释一下。为什么只调用了一次CON后却调用了3次DES。
#include <fstream>
#include <string>
using namespace std;
ofstream out("HowMany.out");
class HowMany {
static int objectCount;
public:
HowMany() { objectCount++;out<<"Constructor called!"<<endl;}
static void print(const string& msg = "") {
if(msg.size() != 0) out << msg << ": ";
out << "objectCount = "
<< objectCount << endl;
}
~HowMany() {
objectCount--;
print("~HowMany()");
}
};
int HowMany::objectCount = 0;
// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}
int main() {
HowMany h;
HowMany::print("after construction of h");
HowMany h2 = f(h);
HowMany::print("after call to f()");
} ///:~