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 ;//函数声明
    };
View Code

(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);
}
View Code

(3)mian.cpp

// 7.8.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "box.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
    const box styleBox(5,2,3);//不希望它发生改变,所以直接声明为const对象
    cout<<"标准盒子创建完成"<<endl;
    box temp(1,1,1);
    while(styleBox.Compare(temp) != true)//注意:此处为styleBox.所以调用的时候,this指针不想改变了
    {
        cout<<"刚才的盒子不合适"<<endl;
        int lenth;
        int width;
        int hight;
        cout<<"请输入新盒子的数据,使它符合标准盒子的大小"<<endl;
        cin>>lenth;
        cin>>width;
        cin>>hight;
        temp = box(lenth,width,hight);
    }
    cout<<"盒子刚好合适,恭喜你"<<endl;
    return 0;
}
View Code

相关推荐