面向对象编程,拷贝构造函数什么时间调用

什么时候调用拷贝构造函数
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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值