C++面向对象高级编程(侯捷)——听课笔记

这篇笔记详细介绍了C++的面向对象编程,涵盖了C++程序的基本形式,包括文件类型、头文件的正规写法、构造函数、参数传递与返回值、友元和操作符重载。强调了构造函数的特性、参数传递的最佳实践以及友元和操作符重载的作用。此外,还提及了C++中的const使用和访问级别设定。
摘要由CSDN通过智能技术生成

欢迎使用Markdown编辑器

0.写在前面

C++语言编写时需要注意的规范:

  1. 数据一定放在private中;
  2. 参数尽可能以reference(const)传递;
  3. 返回值尽量以reference传递;
  4. 在类的本体函数中,能加const的尽量加;
  5. 构造函数使用re(r), im(i) { };

1.C++程序代码的基本形式

1.1 C++文件类型

  • .h文件:
    • 头文件:声明;
    • 标准库.
  • .cpp文件:
    • 主程序;

      • 主程序中引用头文件的声明为***#include"iosteam.h"***形式;
      • 引用标准库的声明为***#include<complex.h>*** .

      扩展名不一定是.h或.cpp,也会根据编译器的不同有所不同,有可能无扩展名。

      // C++代码
      #include <iosteam.h>
      using namespace std;
      int main()
      {
             
      	int i=7;
      	cout << "i="<<i<<endl;
      
      	return 0;
      }
      // C代码
      #include<stdio.h>
      
      int main()
      {
             
      	int i=7;
      	printf("i=%d \n", i);
      
      	return 0;
      }
      

1.2 头文件的正规写法

  • 防卫式声明
//comlex.h
//防卫式声明
#ifndef_COMPLEX_//如果未定义过COMPLEX,不会重复include同一个函数
				//名称一般大写
#define_COMPLEX_//定义COMPLEX函数

.....

#endif//结束
  • 引用程序举例
//complex-test.h
#include <iosteam.h>
#include "complex.h"
using namespace std;

int main()
{
   
	complex c1(2,1);
	complex c2;
	cout<<c1<<endl;
	cout<<c2<<endl;

	c2=c1+5;
	c2=7+c1;
	c2+=c1;
	c2+=3;
	c2=-c1;
	
	cout<<(c1==c2)<<endl;
	cout<<(c1!=c2)<<endl;
	cout<<conj(c1)<<endl;
	
	return 0;
}
  • 头文件的布局
#ifndef_COMPLEX_
#define_COMPLEX_

//前置声明
#include <cmath>

class osteam;
class complex;
complex&_doapl(complex* ths, const complex& r);

//类-声明
class complex
{
   
	...
};

//类-定义
complex::function ...
#endif
  • class-声明举例
class complex	//class head
{
   				//class body
public:
	comlpex(double r=0, double i=0)
		: re (r), im(i)
	{
   }
	complex& operator += (const complex&);
	double real () const{
    return re; }
	double imag () const{
    return im; }
pravite:
	double re, im;

	friend complex&_doapl(copmlex*, const complex&);
};

{
   
	complex c1(2, 1);
	complex c2;
	...
}
  • 模版
template<typename T>//模版的声明
class complex
{
   
public:
	comlpex(T r=0, T i=0)
		: re (r), im(i)
	{
   }
	complex& operator += (const complex&);//此函数无大括号,在此处只是声明
	T real () const{
    return re; }//此两函数有大括号{},即在此处定义
	T imag () const{
    return im; }
pravite:
	double re, im;

	friend complex&_doapl(copmlex*, const complex&);
};

{
   
	complex<double>c1(2.5, 1.5);
	complex<int>c1(2, 6);
}

inline函数的概念:
一个函数在函数本体内定义,是inline函数
inline函数快速性较好,但是函数过于复杂时,不能inline,是否变为inline函数由编译器决定,
上面的

	T real () const{
    return re; 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>