码迷,mamicode.com
首页 > 编程语言 > 详细

c++0.1-----不包含指针的类~~~知识点大综合

时间:2018-07-01 22:05:48      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:内联函数   简单的   避免   替换   efi   clu   功能   public   引入   

  本篇文章包含知识点有:预编译,访问权限,内联函数,常成员函数,构造函数,运算符重载函数,友元。

以代码为示范:

  文件名:ccompex.h  

  文件内容:定义一个简单的复数类。

 1 #ifndef __CCOMPLEX__
 2 #define __CCOMPLEX__
 3 #include <iostream>
 4 #include <ostream>
 5 using namespace std;
 6 class complex{
 7 friend complex& __doapl(complex& com1,const complex& com2);
 8 public:
 9     inline const double& real() const {return re;}
10     inline const double& image() const {return im;}
11     inline complex(double r=0.0,double i=0.0):re(r),im(i){}
12 private:
13     double re;
14     double im;
15 };
16 
17 inline complex & __doapl(complex &com1,const complex& com2)
18 {
19     com1.re+=com2.re;
20     com1.im+=com2.im;
21     return com1;
22 }
23 
24 inline complex & operator+=(complex &com1,const complex& com2)
25 {
26     return __doapl(com1,com2);
27 }
28 
29 inline complex operator+(const complex& com1,const complex& com2)
30 {
31     return complex(com1.real()+com2.real(),com1.image()+com2.image());
32 }
33 inline complex operator+(const complex& com1,const double& dou)
34 {
35     return complex(dou+com1.real(),com1.image());
36 }
37 inline complex operator+(const double& dou,const complex& com1)
38 {
39     return complex(dou+com1.real(),com1.image());
40 }
41 
42  ostream& operator<<(ostream &os,const complex& x)
43 {
44     os<<(<<x.real()<<,<<x.image()<<)<<endl;
45 }
46 
47 #endif // __CCOMPLEX__

 

 

这47行代码包含了几个c++精髓,下面让我娓娓道来~~~

一.预编译:#ifndef---#define---#endif 与#include

#ifndef---#define---#endif 代码在第1,2,47行,功能是避免头文件重复调用,在编译的时候合理将代码替换过来。

头铁不信系列:去掉#ifndef---#define---#endif 后,再多次在主文件包含这个头文件,进行编译,编译器给出以下错误信息:

error: redefinition of ‘class complex‘

错误解析:以上错误信息的意思是说对complex类重定义了。也就是说包含多次该文件,若没有预编译的功能,错误就会出现。

 

#include代码在第3,4行,表示引入一些头文件。

使用方法:系统头文件用<>包住,同时,不需要加.h后缀哦。例如:#include<iostream>

        自定义头文件用" "包住。例如:#include "ccomplex.h"。

 

二.访问权限:

 

c++0.1-----不包含指针的类~~~知识点大综合

标签:内联函数   简单的   避免   替换   efi   clu   功能   public   引入   

原文地址:https://www.cnblogs.com/yulianggo/p/9251290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!