英语不是我的母语,所以请原谅我的语法问题。
当我运行我的程序时,我发现在定义对象和显式调用构造函数时会调用类构造函数。在调用构造函数和离开作用域之后,析构函数被调用了两次。
#include<iostream>
class test {
private:
int a;
int b;
int c;
public:
test(int first = 0, int second = 0, int third=0 );
void show();
~test();
};
void test::show() {
std::cout << this->a<<"\n";
}
test::test(int first , int second , int third ) {
this->a = first;
this->b = second;
this->c = third;
std::cout << "Construct\n";
}
test::~test() { std::cout << "destruct\n"; }
extern test myclassone;
#include <iostream>
#include "myhead.h"
test myclassone;
int main()
{
std::cout << "begain\n";
{
std::cout << "mid\n";
myclassone = test(1,1,1);
std::cout << "mid\n";
myclassone.show();
}
std::cout << "end\n";
}
这个程序的输出是
Construct
begain
mid
Construct
destruct
mid
1
end
destruct
在我的期望中,构造函数和析构函数只会被调用一次。但令人费解的是,根据输出,它们被调用了两次。我google了这个问题,很多答案都没有解释为什么在定义对象时调用构造函数,以及为什么在调用构造函数后立即调用析构函数
你的程序运行如下:
test myclassone;
。main()
叫做。begain
并mid
打印出来。test(1,1,1)
。test(1,1,1)
。mid
被打印。myclassone.show()
叫做。end
被打印。main()
。test myclassone;
因此,构造函数和析构函数为每个对象调用一次,总共调用两次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句