64,685
社区成员
发帖
与我相关
我的任务
分享
# include <fstream>
# include <string>
# include <iostream>
using namespace std;
ofstream out("Test.out");
class Test
{
static int objectCount;
public:
Test()
{
objectCount++;
}
static void print(const string & msg ="")
{
if(msg.size()!=0)
cout<<msg<<":";
cout<<"objectCount ="<<objectCount<<endl;
}
~Test()
{
objectCount--;
print("~Test()");
}
};
int Test::objectCount =0;
Test f(Test t)
{
t.print("t argument inside f()");
return t;
}
int main()
{
Test t;
t.print("after construction of t");
Test t2 =f(t);
t2.print("after call to f()");
return 0;
}
Test(const Test&)
{
printf("in copy\n");
}
# include <fstream>
# include <string>
# include <iostream>
using namespace std;
ofstream out("D:\\Test.out");
class Test
{
static int objectCount;
public:
Test()
{
objectCount++;
}
static void print(const string & msg ="")
{
if(msg.size()!=0)
cout<<msg<<":";
cout<<"objectCount ="<<objectCount<<endl;
}
~Test()
{
objectCount--;
print("~Test()");
}
};
int Test::objectCount =0;
Test f(Test t)
{
t.print("t argument inside f()");
return t;
}
int main()
{
Test t;//这里调用默认构造函数构造t。。所以objectCount++了。。
t.print("after construction of t");
//这里首先调用复制构造函数用t初始化形参t。。然后形参t析构。。
//然后用函数的返回结果,调用赋值构造函数初始化t2。。
//由于这里都是用复制构造函数而不是默认构造函数Test()构造的对象。。所以objectCount没有增加。。
Test t2 =f(t);
t2.print("after call to f()");
return 0;
//最后析构t和t2。。objectCount变为-2。。
}