标签:
Reference: TutorialPoints, GeekforGeeks
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
In C++, if a copy constructor is not defined in a class, the compiler itself defines one.
Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.
1 class Complex { 2 3 private double re, im; 4 5 // A normal parametrized constructor 6 public Complex(double re, double im) { 7 this.re = re; 8 this.im = im; 9 } 10 11 // copy constructor 12 Complex(Complex c) { 13 System.out.println("Copy constructor called"); 14 re = c.re; 15 im = c.im; 16 } 17 18 // Overriding the toString of Object class 19 @Override 20 public String toString() { 21 return "(" + re + " + " + im + "i)"; 22 } 23 } 24 25 public class Main { 26 27 public static void main(String[] args) { 28 Complex c1 = new Complex(10, 15); 29 30 // Following involves a copy constructor call 31 Complex c2 = new Complex(c1); 32 33 // Note that following doesn‘t involve a copy constructor call as 34 // non-primitive variables are just references. 35 Complex c3 = c2; 36 37 System.out.println(c2); // toString() of c2 is called here 38 } 39 }
Output:
Copy constructor
called (10.0 + 15.0i)
1 class Complex { 2 3 private double re, im; 4 5 public Complex(double re, double im) { 6 this.re = re; 7 this.im = im; 8 } 9 } 10 11 public class Main { 12 13 public static void main(String[] args) { 14 Complex c1 = new Complex(10, 15); 15 Complex c2 = new Complex(c1); // compiler error here 16 } 17 }
Compile error
标签:
原文地址:http://www.cnblogs.com/ireneyanglan/p/4941395.html