Class_name(const class_name &old_object);
class A
{
A(A &x) // copy constructor.
{
// copyconstructor.
}
}
#include <iostream> using namespace std; class A { public: int x; A(int a) // parameterized constructor. { x=a; } A(A &i) // copy constructor { x = i.x; } }; int main() { A a1(20); // Calling the parameterized constructor. A a2(a1); // Calling the copy constructor. cout<<a2.x; return 0; }
20
#include <iostream> using namespace std; class Demo { int a; int b; int *p; public: Demo() { p=new int; } void setdata(int x,int y,int z) { a=x; b=y; *p=z; } void showdata() { std::cout << "value of a is : " <<a<< std::endl; std::cout << "value of b is : " <<b<< std::endl; std::cout << "value of *p is : " <<*p<< std::endl; } }; int main() { Demo d1; d1.setdata(4,5,7); Demo d2 = d1; d2.showdata(); return 0; }
value of a is : 4 value of b is : 5 value of *p is : 7
#include <iostream> using namespace std; class Demo { public: int a; int b; int *p; Demo() { p=new int; } Demo(Demo &d) { a = d.a; b = d.b; p = new int; *p = *(d.p); } void setdata(int x,int y,int z) { a=x; b=y; *p=z; } void showdata() { std::cout << "value of a is : " <<a<< std::endl; std::cout << "value of b is : " <<b<< std::endl; std::cout << "value of *p is : " <<*p<< std::endl; } }; int main() { Demo d1; d1.setdata(4,5,7); Demo d2 = d1; d2.showdata(); return 0; }
value of a is : 4 value of b is : 5 value of *p is : 7
副本构造器 | 分配运算符 |
这是一个重载的构造函数。 | 它是按位运算符。 |
它将使用现有对象初始化新对象。 | 它将一个对象的值分配给另一个对象。 |
副本构造函数的语法: Class_name(const class_name&object_name) { //构造函数的主体。 } |
赋值运算符的语法: 类名a,b; b = a; |
使用现有对象初始化新对象时,将调用副本构造函数。 该对象作为参数传递给函数。 它返回对象。 |
当我们将现有对象分配给新对象时,将调用赋值运算符。 |
现有对象和新对象都共享不同的内存位置。 | 现有对象和新对象都共享相同的内存位置。 |
如果程序员未定义副本构造函数,则编译器将自动生成隐式默认副本构造函数。 | 如果我们不重载" ="运算符,则将按位复制。 |