c++ 函数重载

来源:互联网 发布:qq社交软件 编辑:程序博客网 时间:2024/05/16 08:10
#include <iostream>using namespace std;class Complex {         public:Complex() : m_real(1.0),m_imag(2.5){};//这里的m_real和m_imag在后面才被定义        double getValue();        double getValue(double xy)        {cout << "getValue  param xy add then sun m_real = " <<  m_real + xy <<  " ,   m_imag = " << m_imag + xy << endl;    cout << "------------------------------" << endl;                return xy;        };        Complex(double real, double imag)        {             m_real = real;             m_imag = imag;                 }        void toString(){  cout << "m_real = " <<  m_real <<  " ,   m_imag = " << m_imag << endl;    cout << "------------------------------" << endl;}        typedef std::string::size_type index;private :        double    m_real;        double    m_imag;std::string::size_type contents;std::string::size_type height,width;        index content;        index m_height,m_width;};inlinedouble Complex::getValue(){cout << "sun value=" << m_real + m_imag << endl;cout << "------------------------------" << endl;return m_real + m_imag;}int main(){        Complex c1;c1.toString();c1.getValue();c1.getValue(5.0);        Complex c3(2.0,3.5);c3.toString();        c1 = c3;c1.toString();        Complex c2 = Complex(4.0,5.5);c2.toString();        Complex c5(c3);c5.toString();        Complex c4 = c2;  c4.toString(); return 0;       }



输出:

pateo@pateo-B86N53X:~/work/study$ g++ main.cc -o mainpateo@pateo-B86N53X:~/work/study$ ./mainm_real = 1 ,   m_imag = 2.5------------------------------sun value=3.5------------------------------getValue  param xy add then sun m_real = 6 ,   m_imag = 7.5------------------------------m_real = 2 ,   m_imag = 3.5------------------------------m_real = 2 ,   m_imag = 3.5------------------------------m_real = 4 ,   m_imag = 5.5------------------------------m_real = 2 ,   m_imag = 3.5------------------------------m_real = 4 ,   m_imag = 5.5------------------------------pateo@pateo-B86N53X:~/work/study$ 

重载就是方法名一样,参数个数、参数类型和返回类型不一样,与java基本一致

原创粉丝点击