C++入门经典-例7.8-const对象,标准尺寸
生活随笔
收集整理的這篇文章主要介紹了
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//此處就和它比,不再改變了??傊?#xff0c;如果某個對象不想改變,而有函數與不改變的對象有關系,那么久這么弄 { 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?
轉載于:https://www.cnblogs.com/lovemi93/p/7553393.html
總結
以上是生活随笔為你收集整理的C++入门经典-例7.8-const对象,标准尺寸的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SCSS SASS Color 颜色函
- 下一篇: CSS文档优化