C++入门经典-例7.8-const对象,标准尺寸
1:当建立一个对象之后,如果不希望它的任何数据发生改变,可以将其直接声明为const对象,例如:
const 类名 对象名
const对象必须初始化。我们可以调用它的数据和函数,但是不可以对他们进行修改。除此之外,const对象的this指针也还是常量。我们知道,成员函数在自己的函数体内自动为成员变量加上this指针。如何使这些内存指针就转化为const呢?仍然需要const关键字,函数声明形式如下:
返回类型 函数名(参数列表) const;
即在函数头结尾加上const。只能对类中的函数做如此说明,对外部函数无效。
2:代码如下:
(1)box.h
class box{ public: int m_lenth; //长 int m_width; //宽 int m_hight; //高 box(int lenth,int width,int hight); bool Compare(box b) const ;//函数声明 };
(2)box.cpp
#include "stdafx.h" #include <iostream> #include "box.h" using std::cout; using std::endl; box::box(int lenth,int width,int hight) { m_lenth=lenth; m_width=width; m_hight=hight; cout<<"刚刚制作的盒子长:"<<lenth<<"宽:"<<width<<"高:"<<hight<<endl; } bool box::Compare(box b) const//此处就和它比,不再改变了。总之,如果某个对象不想改变,而有函数与不改变的对象有关系,那么久这么弄 { return (m_lenth==b.m_lenth)&(m_width==b.m_width)&(m_hight==b.m_hight); }