美文网首页
拷贝构造函数

拷贝构造函数

作者: 祝方泽 | 来源:发表于2018-07-05 17:03 被阅读0次

浅拷贝(bitwise copy)&深拷贝(memberwise copy)

没有virtual函数

#include <iostream>
#include <string>
using namespace std;

class A {
public:
    A(): n_(0) {
        ptr_ = new char[5];
        for (int i = 0; i < 5; ++ i) ptr_[i] = i + '0';
        s_ = "12345";
    }
    int n_;
    char* ptr_; // bitwise copy
    string s_; // memberwise copy, because string has a copy construct function
};
  
  
int main() {
  A a;
  A b = a;
  for (int i = 0; i < 5; ++ i) b.ptr_[i] = i + 'a';
  b.s_ = "abcde";

  cout << a.ptr_[0] << " " << b.ptr_[0] << endl;
  cout << a.s_ << " " << b.s_ << endl;

  return 0;
}

output:
a a
12345 abcde

类A没有拷贝构造函数,当发生赋值时,编译器必须为其添加一个拷贝构造。对于常规变量,例如int,char是浅拷贝然而string是深拷贝,因为string类存在拷贝构造函数。*

存在virtual函数

#include <iostream>
class Animal {
  public:
    virtual void Run() {...}
};

class Tiger: public Animal {
  public:
    virtual void Run() {...}
};

int main() {
  Tiger tiger;
  // 发生截断
  // 并且,animal的虚指针vptr指向类Animal
  Animal animal = tiger; // memberwise copy
  animal.Run(); // 调用的Animal的Run()
}

相关文章

  • C++语言基础(02)

    1.可变参数 2.构造函数、析构函数、拷贝构造函数 构造函数 拷贝构造函数 //浅拷贝(值拷贝)问题 //深拷贝

  • C++面向对象高级编程(上)-第二周-博览网

    第二周 三大函数:拷贝构造,拷贝赋值,析构 字符串的构造函数,拷贝构造函数, 拷贝构造函数和拷贝赋值函数没有自主定...

  • (GeekBand)Second class

    一、Big Three:拷贝构造函数,拷贝赋值函数,析构函数 1.拷贝构造函数 文字定义:拷贝构造函数,又称复制构...

  • c++:拷贝构造函数&&深浅拷贝

    默认拷贝构造函数的汇编代码: 其实就相当于这一段代码 拷贝构造函数 多态拷贝构造函数 子类拷贝构造函数调用父类拷贝...

  • C++之构造进阶之拷贝构造

    拷贝构造函数的概述 拷贝构造函数的本质是构造函数。 调用拷贝构造的时机:旧对象给新对象初始化。 用户不提供拷贝构造...

  • 博览网--C++面向对象高级编程(上)-- C++学习第二周笔记

    一、拷贝构造, 拷贝赋值, 析构 Class 带指针 , 必须有拷贝构造和拷贝赋值函数 1) 拷贝构造函数: ...

  • C++boolan part1_week2

    Big Three三个特殊函数 (拷贝构造函数、拷贝赋值函数、析构函数) 1 拷贝构造函数 定义:如果一个构造函数...

  • c++11 拷贝控制

    拷贝控制操作包括,拷贝构造函数,拷贝赋值运算符,移动构造函数,移动赋值运算符,析构函数。拷贝和移动构造函数定义了用...

  • 20-拷贝构造函数

    拷贝构造函数(Copy Constructor) 拷贝构造函数,也是构造函数的一种。大家都知道,构造函数是在对象创...

  • C++ 构造函数,类的成员变量

    c++ 05 构造函数无参构造函数有参构造函数 拷贝构造函数 浅拷贝 深拷贝 类的成员变量 四类特殊的成员变量

网友评论

      本文标题:拷贝构造函数

      本文链接:https://www.haomeiwen.com/subject/emwpuftx.html