什么时候调用拷贝构造函数
1、调用函数时,实用是对象,形参不是引用类型
如果函数的形参是引用类型,就不会调用拷贝构造函数
2、函数的返回类型是类,而且不是引用类型
#include<iostream>
#include<Windows.h>
#include<string>
using namespace std;
class Cat
{
public:
Cat(string name, int age);
Cat(const Cat&other);
void eat();
string getName() const;
int getAge() const;
void description() const;
private:
string name;
int age;
};
void Cat::eat()
{
cout << "小猫爱吃鱼" << endl;
}
string Cat::getName() const
{
return name;
}
int Cat::getAge() const
{
return age;
}
Cat::Cat(string name, int age)
{
this->name = name;
this->age = age;
}
void Cat::description() const
{
cout << "姓名: " << name << " 年龄: " << age << endl;
}
Cat::Cat(const Cat&other)
{
cout << "调用拷贝构造函数" << endl;
name = other.name;
age = other.age;
}
void showMsg( const Cat &cat)
{
cout << cat.getName() << "的基本信息" << endl;
cat.description();
}
const Cat & getBetterMan(const Cat &cat1, const Cat &cat2)
{
if (cat1.getAge()>cat2.getAge())
{
return cat1;
}
else
{
return cat2;
}
}
int main()
{
Cat cat1("小梨花",2);
showMsg(cat1); //调用函数时,当实参为对象,形参不是引用的时候调用拷贝构造函数
Cat cat2("小黑",5);
getBetterMan(cat1, cat2); //返回一个临时对象
system("pause");
return 0;
}
3、对象数组的初始化列表中,使用对象。
#include<iostream>
#include<Windows.h>
#include<string>
using namespace std;
class Cat
{
public:
Cat();
Cat(const Cat &other);
void eat();
string getName() const;
int getAge() const;
void description() const;
private:
string name ="xiao";
int age=25;
};
void Cat::eat()
{
cout << "小猫爱吃鱼" << endl;
}
string Cat::getName() const
{
return name;
}
int Cat::getAge() const
{
return age;
}
void Cat::description() const
{
cout << "姓名: " << name << " 年龄: " << age << endl;
}
Cat::Cat(const Cat&other)
{
cout << "调用拷贝构造函数" << endl;
name = other.name;
age = other.age;
}
Cat::Cat()
{
name = "xiaoba";
age = 27;
}
int main()
{
Cat f1, f2, f3, f4;
Cat F4[4] = { f1,f2,f3,f4 };
system("pause");
return 0;
}