#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;
}