c++知识复习
来源:互联网 发布:天下手游激活码淘宝 编辑:程序博客网 时间:2024/05/17 23:37
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
- 【C++】学习、复习知识框架
- C语言知识复习①
- C语言易忘知识记录复习
- C语言小知识复习1
- C语言小知识复习2
- C语言小知识复习3
- C语言重点知识复习1
- C语言重点知识复习2
- 复习知识
- 金融知识复习
- 从零开始复习股票知识
- 操作系统知识复习
- 金融知识复习
- Hibernate知识复习01
- Hibernate知识复习02
- 复习以前的知识
- 二叉树知识复习
- 线程知识复习整理
- LeetCode072 Edit Distance
- 题目1084:整数拆分
- oracle学习笔记
- Spring AOP Annotaion
- 让我来谈谈如何写paper!
- c++知识复习
- 长尾理论
- zoj3953 贪心 training 3
- Boost---在Windows上的入门(1)
- LeetCode Algorithms 5. Longest Palindromic Substring
- Android一整套图片解决方案
- caffe学习(7)------网络迭代时间测试
- 算法 上机 第四题
- 题目1085:求root(N, k)