1.类
在C++中,一般将类的声明放在头文件,将类的实现放在源程序文件中
//rectangle.h
#ifndef __RECTANGLE_H__
#define __RECTANGLE_H__
//上两句话意思是若未定义__RECTANGLE_H__,则定义
class Rectangle
{
private:
int length, width,height;
public:
//构造函数
Rectangle(int len, int wd, int ht) :length(len), width(wd), height(ht){}
//析构函数
virtual ~Rectangle(){}
int Volume() const;
};
#endif
//rectangle.cpp
#include"rectangle.h"
int Rectangle::Volume() const
{
return length*width*height;
}
//main.cpp
#include<iostream>
using namespace std;
#include"rectangle.h"//提供类Rectangle的声明
int main()
{
Rectangle thisRectangle(6, 8, 9);
int volume = 0;
volume = thisRectangle.Volume();
cout << volume << endl;
return 0;
}
2.运算符重载
运算符重载有两种方式
①将运算符重载为全局函数,这种情况下可声明为友元,以便引用类的私有成员,如+重载如下
friend Complex operator+(const Complex&a,const Complex &b)
②将运算符重载为类的成员函数,此时对象自己成了左侧的参数,所以单目运算符没有参数,双目运算符只有一个右侧参数,如-重载
friend Complex operator-(const Complex&a)
实例如下
//complex.h
#ifndef __COMPLEX_H__
#define __COMPLEX_H__
class Complex
{
private:
double realPart,imagePart;//复数的实部与虚部
public:
//构造函数
Complex(double rp=0,double ip=0) :realPart(rp), imagePart(ip){}
//析构函数
virtual ~Complex(void){};
double GetRealPart() const { return realPart; }
double GetImagePart() const { return imagePart; }
void SetRealPart(double rp) { realPart = rp; }
void SetImagePart(double ip){ imagePart = ip; }
void Show() const;
Complex operator -(const Complex &a);//重载为成员函数
};
void Complex::Show() const
{
cout << realPart;
if (imagePart < 0 && imagePart != -1)cout << imagePart << "i" << endl;
else if (imagePart == -1) cout << "-i" << endl;
else if (imagePart > 0 && imagePart != -1)cout << "+" << imagePart << "i" << endl;
else if (imagePart == 1) cout << "+i" << endl;
}
Complex operator+(const Complex &a, const Complex &b)
{//作为全局函数的加法重载
Complex c;
c.SetRealPart(a.GetRealPart() + b.GetRealPart());
c.SetImagePart(a.GetImagePart() + b.GetImagePart());
return c;
}
Complex Complex::operator-(const Complex &a)
{//作为成员函数重载
Complex c;
c.realPart=realPart-a.realPart;
c.imagePart=imagePart-a.imagePart;
return c;
}
#endif
//main.cpp
#include<iostream>
using namespace std;
#include"complex.h"
int main()
{
Complex z1(6, 8);
z1.Show();
Complex z2(8, 9);
z2.Show();
Complex z3;
z3 = z1 + z2;
z3.Show();
Complex z4;
z4 = z2 - z1;
z4.Show();
return 0;
}