1.拷貝構造函數(shù)的參數(shù)最好是類對象的常量引用
2.const限定符有兩個作用疫剃,一是防止被復制的對象被修改,二是擴大使用范圍
有一條編程經驗就是自定義的對象作為參數(shù)傳遞许布,能引用就盡量用引用衩辟,能用常量引用的盡量使用常量引用盐欺。因為被復制的對象有可能是常對象
#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) { //拷貝構造函數(shù)的參數(shù)最好是類對象的常量引用
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();
}