Class and Object shallow vs. deep copy

 The difference between structure and class are: different default access level
Note the use of the class:
• class declaration in the private and public key two times as may appear in any order. In order to make the program more clear, all members of the public and private members categorized together
• In addition to private and public, as well as protected (protective member) Keyword
• Data members can be of any data type, but can not use auto, register or extern Description
• You can not initialize the data members in the class declaration
 
op.setPoint (1,2) actually op.point :: setPoint (1,2) in the abbreviated form, equivalently,
• External functions can not be referenced private members object.
 
The constructor and destructor
Constructor
Conditions constructor call
1. Define object directly call
  Complex A(1.1,2.2);
2. Dynamic allocation of space objects
  Complex *p = new Complex(3.0,4.0);
3. Define unnamed objects (objects with no name)
  Complex(2,4);
  new Complex(4,8);
Constructor with default parameters may be,
Constructors can be overloaded, to adapt to different situations.
Note: a class in both the overloaded constructor, there are default parameters
Constructor, it is possible to produce ambiguous
Destructor
Also a special destructor member functions which performs the reverse operation to the constructor, typically used to perform some clean-up tasks, such as the release of the memory space allocated to the object and the like
Destructor has the following features:
• the same constructor destructor name, but it must be added in front of a tilde (~)
• destructor no parameters and returns no value and can not be overridden, in one class can have a destructor
• When Revoking Object, the compiler will automatically call the destructor
Conditions call destructor
1. Object automatically exit lifecycle
For example: global object, local object
  { Complex A(1.1,2.2);}
  void fun(Complex p){ };
2. programmer manual release object pointer
  Complex *p = new Complex(5,6);
  delete p;
The execution sequence constructor and destructor of a class object within the same scope: the first configuration destructor
 
Copy constructor
The copy constructor is a special constructor.
It is used to create a new object based on an object that already exists. Typically, the object will be represented by domain parameters are copied to the newly created object in
Each class has a constructor that a user can define their own needs, or the system may also generate a default copy constructor for the class
Copy constructor call condition
1. define the object
  Point p1(30,40);
  Point p2(p1);// Point p2 = p1;
2. The parameters of the object function
  void test(Point p);
  test(p1);
3. The return value is a function of object
  Point test();
  test();
 
Tip: do not call the copy constructor to initialize the object using the unnamed object system. Call the constructor
E.g:
Point A = Point(4,5);
Point test(Point p){retrun p;} 
test(Point(4,5))
 
Structure derived class, the base class constructor, member objects construction order:
Base class constructor = "member objects construction order =" derived class constructor
#include<iostream>
#include<string>
using namespace std;
class Third {
public:
    Third() {
        cout<<"third constructor"<<endl;
    }
};
 
class Base {
public:
    Base(string name) {
        cout<<"base constructor"<<endl;
        this->name = name;
    }
    void disp1() {
        cout<<this->name<<endl;
    }
private:
    string name;
};
 
class Derived:public Base {
public:
    Derived(string name, int age):Base(name), third(new Third()) {
    // third (new Third ()), Base (name) wrote the same result
        cout<<"dervied constructor"<<endl;
        this->age = age;
    }
    void disp2() {
        cout<<this->age<<endl;
    }
private:
    int age;
    Third *third;
};
 
int main ()
{
    Derived d("zhangsan", 10);
    d.disp1();
    d.disp2();
    return 0;
}
 
result:
based builder
third constructor
dervied builder
zhangsan
10
 
const member functions modified
Since any member functions can access any data members in the class, but when we do not want to let it modify data members, we can use the modified class member function const
Class class_name {
private:
......
public:
(type) function_name(...)const {
}
};
When modified by const member function, the member function in vivo may not modify any of the data members of the body structure
However, there is a case before the exception is that when a member of the type on a mutable data modification, the const member functions in vivo of the modified data member can be changed
 
Object assignment
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class MyClass{
private:
    int a,b;
    char *p;
public:
    void set(int i,int j){
        a = i;
        b = j;
    }
    void show(){
        cout<<a<<','<<b<<endl;
    }
   //~MyClass() {
    //    delete p;
    //}
};
 
int main ()
{
    MyClass p1;
    MyClass p2;
    p1.set(20,5);
    p2 = p1; // assignment objects
    p2.set(10, 1);
    p1.show();   // 20,5
    p2.show();  // 10,1
    return 0;
}
 
Description:
  1, when a target of assignment for assigning objects, two objects must be the same type, such as different types of objects,
     The compile-time error.
  2, the assignment between the two objects, so that only those data objects with the same members, and the two objects remain separate. E.g
     After the object of the present embodiment, then call p2.set p2 set value, it does not affect the value of p1.
  3, the object is achieved by assigning a default assignment operator function
  4, when the object are assigned a value of another object, are successful in most cases, but in the presence of pointer class, may
     It will generate an error.
 
Shallow vs. deep copy
For the default copy constructor for a shallow copy
Shallow copy: bit copy, the copy constructor, assignment overloading
A plurality of objects share the same resources, a resource release with multiple crash or memory leak
Deep copy: each object together with its own resources, we must explicitly provide a copy constructor and assignment operator.
Shades of difference between copying:
    Shallow copy is a copy of the original object data type fields to the new object to , the reference type field "reference" copied to the new object to, not the "reference object" copied into , so that the original object and the new object reference the same object, the new object reference type fields change will lead to the corresponding fields of the original object is changed.
    Deep copy is different in terms of reference, it is to create a deep copy of the same field a new and original content field, is as big as two pieces of data, so the two references are different, then the new object type in the references field is changed, the original object will not cause a change in the field.
#include<iostream>
#include<string.h>
using namespace std;
class Student {
public:
    Student(char *name, int age): age(age) {
        this->name = new char[strlen(name) + 1];
        strcpy(this->name, name);
    }
    void disp() {
        cout<<name<<endl;
        cout<<age<<endl;
    }
    void setAge(int age) {
        this->age = age;
    }
    void deleteName() {
        delete name;
    }
private:
    char *name;
    int age;
};
int main ()
{
    Student stu1("zhangsan", 1);
    Student stu2 = stu1;
    stu2.setAge(2);
    stu1.disp (); // zhangsan 1
    stu2.disp (); // zhangsan 2
    stu1.deleteName (); // name reference deleted
    stu2.disp (); // " " 2
    return 0;
}
 
The solution: to achieve their own copy constructor
Student(const Student &stu) {
        this->name = new char[strlen(stu.name) + 1];
        strcpy(this->name, stu.name);
}
When there is a pointer in a class data members, using the copy constructor?
If not explicitly declared copy constructor, the compiler will generate a default copy constructor, and runs in the general case is also good. However, problems arise in the event class has a pointer to data members: default copy constructor because the press member is a copy constructor, which results in two different pointers (e.g. ptr1 = ptr2) pointing to the same memory. When an instance destroyed, calling the destructor free (ptr1) released this memory, the pointer ptr2 an instance of the rest is invalid, an error occurs when free (ptr2) is destroyed, which is quite repeat to release a block of memory twice. This situation must be explicitly declared and implement their own copy constructor, to allocate memory for a new pointer to the new instance.        
 
Copy constructor can call it private member variables?
ANSWER: Hinako we know that when the copy constructor is a special constructor that time, the class member variables or their operation, so unrestricted private.
 
The following function which is the copy constructor, why? Overloadable
X :: X (const X &); // copy constructor
X::X(X);
X :: X (X &, int a = 1); // copy constructor
X :: X (X &, int a = 1, int b = 2); // copy constructor
Solution: For a class X, if the first argument of the constructor is one of the following:
   a) X&
   b) const X&
   c) volatile X&
   d) const volatile X&
  Then this is the copy constructor function.
 
A class may be more than one copy constructor function?
   Answer: there may be more than one class copy constructor.
class X {
public:
  X (const X &); // const copy constructor
  X (X &); // non-const copy constructor
};
Note that if a class there is only one parameter is X & copy constructor, then the object can not be used or volatile X const X copy initialization implementation.
If a class does not define a copy constructor, the compiler will automatically generate a default copy constructor.
This default parameter may be X :: X (const X &) or X :: X (X &), by the compiler according to decide which context.
 
Copy constructor function can not be generated by a template member.
struct X {   
    template<typename T>   
    X( const T& );    // NOT copy ctor, T can't be X   
  
    template<typename T>   
    operator=( const T& );  // NOT copy ass't, T can't be X   
};   
The reason is simple, template member function does not change the rules of the language, and the rules of the language that if the program requires a copy constructor and you do not declare it, the compiler will automatically generate one for you, so members will not function template prevent the compiler generates a copy constructor, assignment operator overloading follow the same rules.
 
Cutting solve the problem:
#include<iostream>
#include<string.h>
using namespace std;
 
class Base {
public:
    virtual void disp() {
        cout<<"Base::disp"<<endl;
    }
};
class Dervied:public Base {
public:
     virtual void disp() {
        cout<<"Dervied::disp"<<endl;
    }
};
void print (Base b) // modify Base & b ok references
{
    cout<<"print"<<endl;
    b.disp ();
}
int main(int argc, char *argv[])
{
    Dervied d;
    print(d);  //print  Base::disp
    return 0;
}
 

Guess you like

Origin www.cnblogs.com/gschain/p/11244960.html