浅拷贝(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()
}