求专家解释------C++匿名对象
程序代码及结果如下:允许结果如何解释?
- C/C++ code
#include <iostream>using namespace std;#include <cstring>class A{ int data; char str[20];public: A():data(0){ cout << "A()" << "--" << this << endl; } A(int d):data(d){ cout << "A(" << d << ")" << "---"<< this << endl; strcpy(str,"qwe"); } ~A(){ cout << "~A()" << data <<"---" << this << "---" << str << endl; } void show(){ cout << "data=" << data <<"---"<< this << endl; }};int main(){ A a1(1); A(2); A(3).show(); cout << "========" << endl; A a4; a4 = A(4); }
输出:
- C/C++ code
A(1)---0x22cc20A(2)---0x22cc38~A()2---0x22cc38---qweA(3)---0x22cc50data=3---0x22cc50~A()3---0x22cc50---qwe========A()--0x22cc08A(4)---0x22cc68~A()4---0x22cc68---qwe~A()4---0x22cc08---qwe~A()1---0x22cc20---qwe
[解决办法]
很奇怪,我运行的结果跟你的有点出入
A(1)---0x0012ff4c 1
A(2)---0x0012ff1c 2
~A()2---0x0012ff1c---qwe 3
A(3)---0x0012ff1c 4
data=3---0x0012ff1c 5
~A()3---0x0012ff1c---qwe 6
========
A()--0x0012ff34 7
A(4)---0x0012ff1c 8
~A()4---0x0012ff1c---qwe 9
~A()4---0x0012ff34---qwe 10
~A()1---0x0012ff4c---qwe 11
第1行与第2行由于它们都是在本上申请的空间,所以地址应该是向下增长的,所以对你的运行结果表示怀疑
[解决办法]