c++知识复习

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值