zoukankan      html  css  js  c++  java
  • c++语言 const函数的使用

    //在类中采取了不少的有效措施以增强数据的安全性,例如使用private,但是有些数据往往需要共享,所以有时无意之中的误操作便会改变有关的数据,这时可以使用const修饰符,即把有关的成员声明为常量.
    //**不能在构造函数的定义中为常成员变量赋初值.
    //**可以使用参数初始化表对const型成员变量进行初始化.如:CShop::CShop(int size):m_size(size){}
    //const函数的使用
    
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    class CShop
    {
    private:
        int m_height;
        int m_weight;
    public:
        CShop(int height, int weight);
        void display() const; //声明一个常成员函数
    };
    CShop::CShop(int height, int weight)
    {
        m_height = height;
        m_weight = weight;
    }
    void CShop::display() const
    {
        cout << "这个人的身高:" << m_height << endl;
        cout << "这个人的体重:" << m_weight << endl;
    }
    
    int main(int argc, char* argv[])
    {
        //printf("Hello World!\n");
        CShop shop(170, 120);
        shop.display();
    
        return 0;
    }
  • 相关阅读:
    hlgoj 1766 Cubing
    Reverse Linked List
    String to Integer
    Bitwise AND of Numbers Range
    Best Time to Buy and Sell Stock III
    First Missing Positive
    Permutation Sequence
    Next Permutation
    Gray Code
    Number of Islands
  • 原文地址:https://www.cnblogs.com/pythonschool/p/2762462.html
Copyright © 2011-2022 走看看