Dog.h文件
#include <iostream>
#include <string>
using namespace std;
#ifndef DOG_H
#define DOG_H
class Dog {
private:
string name;
int age;
static int count;
public:
void bark() {
cout << Dog::name << " age:" << Dog::age << endl;
};
Dog() {
cout << "deflut constractor" << endl;
}
Dog(string name, int age){
Dog::name = name;
Dog::age = age;
Dog::count += 1;
cout << "constractor" << endl;
};
Dog(const Dog & dog){
cout << "copy constractor" << endl;
Dog::name = dog.name;
Dog::age = dog.age;
}
void changeName(string newName) {
name = newName;
}
static int getCount() {
return count;
}
};
#endif
main函数
#include "stdafx.h"
#include <iostream>
#include "Dog.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Dog dog = { "Bob", 5 };
Dog dog2;
dog2 = dog;
dog.bark();
dog.changeName("Tom");
dog.bark();
getchar();
}
输出
constractor
default constractor
Bob age:5
Tom age:5
说明dog2 = dog 并没有调用拷贝构造函数,而是直接执行了按位拷贝。
如果改为Dog dog2 = dog;也就是在定义的时候直接初始化的话就会调用拷贝构造函数;
总结拷贝构造函数调用情况如下:
1:在定义对象时直接用另一个对象对其进行初始化操作时,如 S s1= s2; S s1(s2);
2:在用类对象作为形参时,实参和形参之间传值会调用拷贝构造函数
3:在return一个对象时,函数会生成一个临时的对象,然后调用拷贝构造函数,将return的对象拷贝给临时对象返回给函数。