【C++新特性——委托构造函数和继承构成函数】

委托构造:一个构造调用另一个构造函数

冗余版:

#include<iostream>
using namespace std;

class Test {
public:
    Test(int max)
    {
        this->m_max = max > 0 ? max : 100;
    }

    Test(int max, int min)
    {
        this->m_max = max > 0 ? max : 100;              // 冗余代码
        this->m_min = min > 0 && min < max ? min : 1;
    }

    Test(int max, int min, int mid)
    {
        this->m_max = max > 0 ? max : 100;             // 冗余代码
        this->m_min = min > 0 && min < max ? min : 1;  // 冗余代码
        this->m_middle = mid < max&& mid > min ? mid : 50;
    }


	int m_max;
	int m_min;
	int m_middle;
};

int main()
{
    Test x(3,1,2);
    cout << x.m_max << " " << x.m_middle << " " << x.m_min << endl;

	return 0;
}

委托版:链式调用,注意不要环状(闭环)

#include<iostream>
using namespace std;

class Test {
public:
    Test(int max)
    {
        this->m_max = max > 0 ? max : 100;
    }

    Test(int max, int min):Test(max)
    {
        //Test(max);   不要写到函数体内,这样会出现形参重复
        //this->m_max = max > 0 ? max : 100;              // 冗余代码
        this->m_min = min > 0 && min < max ? min : 1;
    }

    Test(int max, int min, int mid):Test(max,min)
    {
        //this->m_max = max > 0 ? max : 100;             // 冗余代码
        //this->m_min = min > 0 && min < max ? min : 1;  // 冗余代码
        this->m_middle = mid < max&& mid > min ? mid : 50;
    }


	int m_max;
	int m_min;
	int m_middle;
};

int main()
{
    Test x(3,1,2);
    cout << x.m_max << " " << x.m_middle << " " << x.m_min << endl;

	return 0;
}

继承构造:

#include<iostream>
using namespace std;
class base {
public:
	base(int a) :a(a) { 
		cout << "a:" << a << endl;
	};	
	base(int a,int b) :a(a),b(b) {
		cout << "a:" << a << " b:" << b << endl;
	};	
	base(int a,int b,int c) :a(a),b(b),c(c) {
		cout << "a:" << a << " b:" << b << " c:" << c << endl;
	};	

	int a, b, c;
};

class son : public base {
public:
	//常规:
	//son(int a) :base(a) { cout << "a:" << a << endl; };
	//son(int a,int b) :base(a,b) { cout << "a:" << a << " b:" << b << endl; };
	//son(int a,int b,int c) :base(a,b,c) { cout << "a:" << a << " b:" << b << " c:" << c << endl; };

	using base::base;   //继承构造法

};


int main()
{
	son s(1,3,4);


	return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值