C++ 构造函数和析构函数的顺序
下面是一段代码:C++ 构造函数和析构函数的顺序,c++,constructor,destructor,C++,Constructor,Destructor,下面是一段代码: #include<iostream> using namespace std; class cls { int x; public: cls(int i=0) {cout<<" c1 "; x=i;} ~cls() {cout<<" d 1 ";} }; class cls1 { int x; cls xx; public: cls1(int i=0){cout<<"
#include<iostream>
using namespace std;
class cls
{
int x;
public:
cls(int i=0) {cout<<" c1 "; x=i;}
~cls() {cout<<" d 1 ";}
};
class cls1
{
int x; cls xx;
public:
cls1(int i=0){cout<<" c2 ";x=i;}
~cls1(){cout<<" d2 ";}
}c;
class cls2
{
int x;cls1 xx;cls xxx;
public:
cls2(int i=0) {cout<<" c3 ";x=i;}
~cls2(){ cout<<" d3 ";}
};
int main()
{
cls2 s;
return 0;
}
#包括
使用名称空间std;
cls类
{
int x;
公众:
cls(inti=0){cout
我需要一些帮助
代码的一个目的似乎是混淆错误的类名、误导性的实例名等
抵制混淆的一个想法是找到并实践编码标准
下面的代码是上面的代码,它是我喜欢的编码标准的简单替换
看看这一点,看看你是否能就你不理解的东西提出问题
注意—“d1”不会出现在你的代码中,而是显示在你的输出中。因此,你的输出不是来自你发布的代码。我假设它是简单的打字错误
注意Foo_t和Bar_t是如何在main()之前构造的
注意这两个DTR是如何在main(FINI)之后运行的
祝你好运。你能清楚地说明你需要哪种帮助吗?成员在构造函数体执行之前就被初始化了。你能更准确地说是哪一部分让你困惑吗?你打印的数字和类名中的数字不一样真的让人困惑。我想初始化部分…所以当一个成员被初始化时,构造函数被调用?不,我以前没有看到这个问题..对不起,也许还有另一个“改进”…每个类实例都应该有一个唯一的序号…所以其中一个“Foo\u t:c1”可以打印一个不同的值。另一个想法是向ctor添加一个整数参数,捕获到一个数据属性,并使用新参数作为行调用ctor。这将为每个实例化填充唯一的原始行号,以增强cout。
#include <chrono>
// 'compressed' chrono access --------------vvvvvvv
typedef std::chrono::high_resolution_clock HRClk_t; // std-chrono-hi-res-clk
typedef HRClk_t::time_point Time_t; // std-chrono-hi-res-clk-time-point
typedef std::chrono::microseconds US_t; // std-chrono-microseconds
using namespace std::chrono_literals; // support suffixes like 100ms, 2s, 30us
// examples:
//
// Time_t start_us = HRClk_t::now();
//
// auto duration_us = std::chrono::duration_cast<US_t>(HRClk_t::now() - start_us);
// auto count_us = duration_us.count();
// or
// std::cout << " complete " << duration_us.count() << " us" << std::endl;
#include <iostream>
// classes are types, so suffix with _t
// do not 'using namespace std;
class Foo_t // was cls
{
int x;
public:
Foo_t(int i=0) {std::cout<<" Foo_t: c1 \n"; x=i;}
~Foo_t() {std::cout<<" ~Foo_t: d1 \n";} // typo fixed
};
class Bar_t // was cls1
{
int x;
Foo_t xx;
public:
Bar_t(int i=0){std::cout<<" Bar_t: c2 \n"; x=i;}
~Bar_t() {std::cout<<" ~Bar_t: d2 \n";}
} bar;
class Zep_t // was cls2
{
int x;
Bar_t xx;
Foo_t xxx;
public:
Zep_t(int i=0) {std::cout<<" Zep_t: c3 \n"; x=i;}
~Zep_t() { std::cout<<" ~Zep_t: d3 \n";}
};
class T490_t
{
public:
T490_t() = default;
~T490_t() = default;
int exec()
{
Zep_t z;
return(0);
}
}; // class T490_t
int main(int , char** )
{
std::cout << "\n main() start\n" << std::endl;
Time_t start_us = HRClk_t::now();
int retVal = -1;
{
T490_t t490;
retVal = t490.exec();
}
auto duration_us = std::chrono::duration_cast<US_t>(HRClk_t::now() - start_us);
std::cout << "\n FINI " << duration_us.count() << " us\n" << std::endl;
return(retVal);
}
Foo_t: c1
Bar_t: c2
main() start
Foo_t: c1
Bar_t: c2
Foo_t: c1
Zep_t: c3
~Zep_t: d3
~Foo_t: d1
~Bar_t: d2
~Foo_t: d1
FINI 33 us
~Bar_t: d2
~Foo_t: d1