c++ 重载构造函数示例

来源:互联网 发布:赖远明院士怎么样知乎 编辑:程序博客网 时间:2024/04/27 19:52

/*******************************************************
 *author:彭晓林
 *copyright: 版权所有,翻版不究】
 *function: 构造函数缺省参数测试
 ******************************************************/

#include <iostream>
#include <string>

using namespace std;

class SUM
{
 public:
  SUM();
  SUM(int a, int b);
  SUM(float a, float b);
  
  void print();
 private:
  double Total;
};

int main()
{
 SUM a;
 a.print();

 SUM aInt(1,2);
 aInt.print();

 SUM aFloat(1.2f, 1.3f);
 aFloat.print();

 while(1);
}
SUM::SUM()
{
 Total = 0;

 cout<<"无参构造函数被调用"<<endl;
 cout<<"No Parameter Sum is "<<Total<<endl;;
}
SUM::SUM(int a, int b)
{
 Total = a + b;

 cout<<"Int构造函数被调用"<<endl; 
 cout<<"Int Parameter Sum is "<<Total<<endl;; 
}
SUM::SUM(float a, float b)
{
 Total = a + b;

 cout<<"float构造函数被调用"<<endl;
 cout<<"float Parameter Sum is "<<Total<<endl;; 
}

void SUM::print()
{
 cout<<"The Total is "<<Total<<endl; 
}