代码分离
demo.h
class CComplex //定义复数类
{
double m_fReal, m_fImag;//成员变量
public:
CComplex(double r = 0, double i = 0) : m_fReal(r), m_fImag(i) {} //构造函数
double GetReal() { return m_fReal; }//成员函数,返回复数的实部
double GetImag() { return m_fImag; }//成员函数,返回复数的虚部
CComplex operator +(CComplex&); //重载运算符+
CComplex operator +(double); //重载运算符+
};
demo.cpp
#include "test.h"
void main()//主函数
{
CComplex c1(2.3,5.5),c2(3.6,6.8),c3;//复数类对象
test().showResult(c1,c2,c3);
}
CComplex CComplex::operator + (CComplex &c) //重载运算符+,实现两个复数的加法
{
CComplex temp;
temp.m_fReal = m_fReal + c.m_fReal;
temp.m_fImag = m_fImag + c.m_fImag;
return temp;
}
CComplex CComplex::operator + (double d) //重载运算符+,实现复数与实数的加法
{
CComplex temp;
temp.m_fReal = m_fReal + d;
temp.m_fImag = m_fImag;
return temp;
}
test.h
#include"demo.h"
class test
{
public:
virtual void showResult(CComplex c1, CComplex c2, CComplex c3);
test();
~test();
};
test.cpp
#include "test.h"
#include <iostream>
using namespace std;
void test::showResult(CComplex c1, CComplex c2, CComplex c3)
{
cout << "使用重载的+运算符实现复数与复数的相加" << endl;
cout << "C1 = " << c1.GetReal() << "+j" << c1.GetImag() << endl;
cout << "C2 = " << c2.GetReal() << "+j" << c2.GetImag() << endl;
c3 = c1 + c2;
cout << "C3 = C1 + C2 =" << c3.GetReal() << "+j" << c3.GetImag() << endl;
cout << "使用重载的+运算符实现复数与实数的相加" << endl;
c3 = c3 + 6.5;
cout << "C3 + 6.5 = " << c3.GetReal() << "+j" << c3.GetImag() << endl;
}
test::test()
{
}
test::~test()
{
}
其实一个cpp文件即可完成上面的代码,这里之所以分离出来是为了更好帮助大家理解C++。
1.h中基本都会有一个class对象,尽管可以不写,但是需要保持这个习惯:h中负责申明对象,和虚函数,然后在引用该h的cpp中实现该虚函数,切记h文件中不要自己申明自己实现。
2.尽量将class大写 这样和java比较像了
模板
#include <iostream>
#include <string>
using namespace std;
template <class T> //定义函数模板
T Min(T a, T b,T c)
{
if(a<b)
b=a;
return b<c?b:c; //返回b、c中的小值
}
int main() //主函数
{
cout<<"使用模板函数求不同类型数据的最小值"<<endl<<endl;
int i1 = 2, i2 = 6, i3 = 4;
double d1 = 3.4, d2 = 7.2, d3 = 3.39;
string str1("one"), str2("two"),str3("three");
cout << " int类型:"<<i1<<", "<<i2<<", "<<i3 <<" 最小值: " << Min(i1, i2, i3) << endl<<endl; //int型的最大值
cout << " double类型:" <<d1<<", "<<d2<<", "<<d3 <<" 最小值:" << Min(d1, d2, d3) << endl<<endl; //double型的最大值
cout << " string类型:" <<str1<<", "<<str2<<", "<<str3 <<" 最小值:"<< Min(str1, str2, str3) << endl<<endl; //string型的最大值
return 0;
}
获取数组长度
#include <iostream>
using namespace std;
template<class T>
int getArrayLen(T &array) /*使用模板定义一个函数getArrayLen,该函数将返回数组array的长度*/ {
return (sizeof(array) / sizeof(array[0]));
}