1.拷贝构造函数的参数最好是类对象的常量引用
2.const限定符有两个作用,一是防止被复制的对象被修改,二是扩大使用范围
有一条编程经验就是自定义的对象作为参数传递,能引用就尽量用引用,能用常量引用的尽量使用常量引用。因为被复制的对象有可能是常对象
#pragma warning(disable:4996)
#include<iostream>
#include <cstring>
using namespace std;
class Person {
char* pName;
public:
Person(const char* pN = "noName") {
cout << "Constructing " << pN << endl;
pName = new char[strlen(pN) + 1];
if (pName) {
strcpy_s(pName, strlen(pN) + 1, pN);
}
}
Person(const Person& s) { //拷贝构造函数的参数最好是类对象的常量引用
cout << "copy Cpnstructing " << s.pName << endl;
pName = new char[strlen(s.pName) + 1];
if (pName) {
strcpy(pName, s.pName);
}
}
~Person() {
cout << "Destructing222 " << pName << endl;
delete[] pName;
}
void print() {
cout << pName << endl;
}
};
int main() {
Person p1("David");
Person p2(p1);
p1.print();
}