
C++关于拷贝构造函数的程序题
#include<iostream>usingnamespacestd;classtest{private:inta;public:~test(){cout<<"cons...
#include <iostream>
using namespace std;
class test
{
private:
int a;
public:
~test(){cout<<"constructor"<<endl;}
test(int a){cout<<a<<endl;}
test(const test&_test)
{
a=_test.a;
cout<<"Copy constructor"<<endl;
}
};
int main()
{
test A(3);
return 0;
}
这题运行结果是 3 destructor
test(const test&_test)这段应该是属于拷贝构造函数吧,关于拷贝构造函数一直不太明白应该怎么用,这题里貌似也没用上,应该在什么时候用呢??
还有个小问题,析构函数不是只能出现一次么,这题有两个,运行时候也通过了,但是结果显示的是第二个,那第一个析构函数是干什么用的?? 展开
using namespace std;
class test
{
private:
int a;
public:
~test(){cout<<"constructor"<<endl;}
test(int a){cout<<a<<endl;}
test(const test&_test)
{
a=_test.a;
cout<<"Copy constructor"<<endl;
}
};
int main()
{
test A(3);
return 0;
}
这题运行结果是 3 destructor
test(const test&_test)这段应该是属于拷贝构造函数吧,关于拷贝构造函数一直不太明白应该怎么用,这题里貌似也没用上,应该在什么时候用呢??
还有个小问题,析构函数不是只能出现一次么,这题有两个,运行时候也通过了,但是结果显示的是第二个,那第一个析构函数是干什么用的?? 展开
2个回答
展开全部
你好
楼主请见下面的注释 给你详细解答了
(如果还有问题 加q2458483878 我们细聊)
#include <iostream>
using namespace std;
class test
{
private:
int a;
public:
test(int a){cout<<a<<endl;} //这是构造函数
test(const test&_test) //这是复制构造函数 也称为拷贝构造函数
{
a=_test.a;
cout<<"Copy constructor"<<endl;
}
~test(){cout<<"constructor"<<endl;}//这是析构函数 本程序只有这一个析构函数
};
int main()
{
test A(3);
test B=A;//这是可以调用拷贝构造函数
return 0;
}
希望能帮助你哈
楼主请见下面的注释 给你详细解答了
(如果还有问题 加q2458483878 我们细聊)
#include <iostream>
using namespace std;
class test
{
private:
int a;
public:
test(int a){cout<<a<<endl;} //这是构造函数
test(const test&_test) //这是复制构造函数 也称为拷贝构造函数
{
a=_test.a;
cout<<"Copy constructor"<<endl;
}
~test(){cout<<"constructor"<<endl;}//这是析构函数 本程序只有这一个析构函数
};
int main()
{
test A(3);
test B=A;//这是可以调用拷贝构造函数
return 0;
}
希望能帮助你哈
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询