zoukankan      html  css  js  c++  java
  • 派生类的拷贝中记得拷贝基类的内容(手写的话)

    如果你没有new,可以使用默认的拷贝构造函数和默认的operator=,她会自动帮你完善

    手写拷贝使用的两个函数

    1,拷贝构造函数

    2,operator=函数

    class A
    {
    public:
    	int a;
    	A(int x) :a(x){};
    };
    
    class B:public A
    {
    private:
    	int b;
    public:
    	B(int x, int y) :A(x), b(y){}
    	B(const B& x) :A(x), b(x.b){}//1.可以模仿构造函数。2.由于调用了A(x),不需要另外写a(x.a)
    	B& operator=(const B& x)
    	{
    		A::operator=(x);//operator=拷贝父类
    		b = x.b;
    		return *this;
    	}
    	void display()
    	{
    		cout << a <<" "<< b << endl;
    	}
    
    };
    
    int main()
    {
    	B a(1,3);
    	a.display();
    	B b(2, 3);
    	b.display();
    	b = a;          //测试operator=函数
    	b.display();
    	B c(a);          //测试拷贝构造函数
    	c.display();
    }
    

      

  • 相关阅读:
    一条SQL的执行流程
    LinkedList源码解析
    MinorGC前检查
    AbstractList源码分析
    JVM常用命令
    CountDownLatch源码解析
    ReentrantLock源码解析
    HTTPS简单介绍
    工厂方法模式
    观察者模式
  • 原文地址:https://www.cnblogs.com/vhyc/p/5585203.html
Copyright © 2011-2022 走看看