拷贝函数的形式?c++
答案:3 悬赏:80
解决时间 2021-02-20 05:08
- 提问者网友:月葬花瑰
- 2021-02-19 07:31
拷贝函数的形式?c++
最佳答案
- 二级知识专家网友:没感情的陌生人
- 2021-02-19 08:19
对于普通类型的对象来说,它们之间的复制是很简单的,例如:
int a=100;
int b=a;
而类对象与普通对象不同,类对象内部结构一般较为复杂,存在各种成员变量。下面看一个类对象拷贝的简单例子。 #include
using namespace std;
class CA
{
public:
CA(int b)
{
a=b;
}
void Show ()
{
cout<
using namespace std;
class CA
{
public:
CA(int b)
{
a=b;
}
CA(const CA& C)
{
a=C.a;
}
void Show()
{
cout<
using namespace std;
class CA
{
public:
CA(int b,char* cstr)
{
a=b;
str=new char[b];
strcpy(str,cstr);
}
CA(const CA& C)
{
a=C.a;
str=new char[a]; //深拷贝
if(str!=0)
strcpy(str,C.str);
}
void Show()
{
cout<
}
~CA()
{
delete str;
}
private:
int a;
char *str;
};
int main()
{
CA A(10,"Hello!");
CA B=A;
B.Show();
return 0;
}
int a=100;
int b=a;
而类对象与普通对象不同,类对象内部结构一般较为复杂,存在各种成员变量。下面看一个类对象拷贝的简单例子。 #include
using namespace std;
class CA
{
public:
CA(int b)
{
a=b;
}
void Show ()
{
cout<
using namespace std;
class CA
{
public:
CA(int b)
{
a=b;
}
CA(const CA& C)
{
a=C.a;
}
void Show()
{
cout<
using namespace std;
class CA
{
public:
CA(int b,char* cstr)
{
a=b;
str=new char[b];
strcpy(str,cstr);
}
CA(const CA& C)
{
a=C.a;
str=new char[a]; //深拷贝
if(str!=0)
strcpy(str,C.str);
}
void Show()
{
cout<
~CA()
{
delete str;
}
private:
int a;
char *str;
};
int main()
{
CA A(10,"Hello!");
CA B=A;
B.Show();
return 0;
}
全部回答
- 1楼网友:星痕之殇
- 2021-02-19 09:42
class A
{
public:
A(a,b,c)
{
x=a; y=b; z=c;}
A(&d) //拷贝构造函数
{ x=d.a;
y=d.b;
z=d.c;}
private:
x,y,z;
}
- 2楼网友:糜废丧逼
- 2021-02-19 08:55
给你来个简单的例子吧 自己打的 别嫌潦草!!
class A
{
public:
A(a,b,c)
{ x=a; y=b; z=c;}
A(&d) //拷贝构造函数,此函数的参数是类对象
{x=d.a;
y=d.b;
z=d.c;}
private:x,y,z;
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯