默认构造函数、复制构造函数、赋值构造函数

#include <iostream>
#include <typeinfo>
#include <vector>
#include <algorithm>
using namespace std;

class Person
{
    public:
        Person(int x, int y=0, int z=0):mId(x), mAge(y), test(z){
            print();
            cout << "Person" << endl; 
            }

        void operator = (const Person& per){
            // mId = 1;
            per.print();
            cout << "operator = (const Person& per)" << endl; }

        Person(const Person& per){
            // mId = 1;
            print();
            cout << "Person(const Person& per)" << endl; }            
 
        virtual void print() const
        {
            cout << "id: " << mId
                 << ", age: " << mAge << endl;
        }

    protected:
        int mId;
        int mAge;
        int test;
};


int main()
{
    Person p1 = {1,2,3};
    Person p2 = {1};
    Person p3 = p1;
    Person p4(p1);
    Person p5{1};
    p5 = p1;

    return 0;
}

输出:
在这里插入图片描述

default constrctor

第一种的initialization list(初始化列表)构造比第二种inline expansion(内联展开)构造更高效:

  • 初始化列表在构造函数时,把成员变量的值直接放进内存,最快。
    而用内联展开的方式,在成员变量构造好后,再增加对成员变量的赋值操作,把初值放进内存中。慢!
Person(int x, int y=0, int z=0):mId(x), mAge(y), test(z){
}
 // 或者(这两种等效)
Person(int x, int y=0, int z=0){
 	mId = x;
 	mAge = y;
 	test = z;
}

initialization list 调用方式:

Perso P1 = {123} //因为有两个默认参数,所以可以只传递一个参数:P1 = {1} 

inline expansion 调用方式:

Perso P1(1);

copy construnctor

复制构造函数,调用方式:

Person p2(p1)
// 或者
Person p3 = p1;

copy assignment constructor

赋值构造函数,调用方式:

Person P1{1}, p2{2};
p1 = p2;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值