c++面向对象程序设计 笔记二

#带指针的类与无指针的类的区别。

1.头文件添加 guard 防卫式声明,防止重复引入头文件     

2.头文件的布局

包括 前置声明 ,类声明, 类定义

栗子:

class complex
{
public:
	complex(double r = 0, double i = 0)
		:re(r), im(i)
	{

	}
	complex& operator += (const complex&);
	double real() const { return re; }
	double imag() const { return im; }
private:
	double re, im;

	friend complex& _doapl(complex*, const complex&);
};
template <typename T>
class complex
{
public:
	complex(T r = 0, T i = 0)
		:re(r), im(i)
	{

	}
	complex& operator += (const complex&);
	T real() const { return re; }
	T imag() const { return im; }
private:
	T re, im;

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

注:

1.函数若在class body 内定义完成,成为inline候选。inline在类外写在实现的body前面。

2.访问级别 access level :public private 等等

3.ctor 构造函数:默认实参  初值列  赋值 (在初值列中初始化数据 不要在构造函数里初始化(前者为初始化,后者为赋值,虽然效果一样,但时机和效率不同))

4.构造函数可以有很多个重载 (编译器生成独一无二的名称) 注意不能让调用有二义性(同函数重载)

5.ctor放在private区域  (例如 单例模式)


class A
{
public:
	static A& getInstance();
	setup(){...}
private:
	A();
	A(const A& rhs);
};

A& A::getInstance()
{
	static A a;
	return a;
}

6.常量成员函数  【】const修饰 this 不会改变this中的内容 【】如果不是常量费成员函数 使用者无法使用常量对象调用。

7.参数传递:-pass by value- vs. -pass by reference(to const)- 

尽量传引用。

8.返回值传递:return by value vs. return by reference(to const)

返回值也尽量传引用(注意临时对象的情况)

9.friend(友元)

inline complex& _doapl(complex* ths, const complex& r)
{
	ths->re = r.re;
	ths->im = r.im;
	return *ths;
}

 相同class的各个objects互为friends友元

10. 操作符重载

成员函数和非成员函数 重载等等

11.传递者无需知道接受者是以refrence形式接收

inline complex&
_doapl(complex* ths, const complex& r)
{

    return *ths;
}

inline complex&
complex::operator +=(const complex& r)
{
    return _doapl(this, r);
}

{


 c3 += c2+=c1;
}

12.local object不能以引用或者指针返回

13.typename(); 临时对象 匿名对象

14.重载 <<

ostream&
operator << (ostream& os, const complex& x)
{
    return os << "(" << real(x) << "," << imag(x) << ")";
}
发布了44 篇原创文章 · 获赞 5 · 访问量 1397

猜你喜欢

转载自blog.csdn.net/qq_33776188/article/details/104621234