码迷,mamicode.com
首页 > 编程语言 > 详细

C++

时间:2016-05-30 23:08:09      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

对于常类型 有以下几点 要注意:

 首先可归为 : 常数据成员 const 类型  元素;

                   

 #include <iostream>
using namespace std;
class S
{
public :

    S(int i, int j):m(i),n(j)//只能通过构造函数的成员初始化列表对常数据成员进行初始化
    {

    }

    void display()
    {
        cout<<"m = "<<m<<endl;
        cout<<"n = " << n<<endl;
    }
private :
    const int m ;
    const int n ;
};
int main()
{
   S s(1,2);
   s.display();
    return 0;
}

 常对象       const  类名 对象名【参数列表】;

  

#include <iostream>
using namespace std;
class S
{
public :

    S(int i, int j)
    {
        m = i;
        n = j;
    }

    void display()
    {
        cout<<"m = "<<m<<endl;
        cout<<"n = " << n<<endl;
    }
private :
     int m , n;
};
int main()
{
   S const s(1,2);
   ///s.display();禁止的 不允许 常对象 调用 普通成员函数
    return 0;
}

  常函数       数据类型  函数名【参数列表】const;

#include <iostream>
using namespace std;
class S
{
public :

    S(int i, int j)
    {
        m = i;
        n = j;
    }

    void  setvalue( ) const
    {
     cout<<" this is const 函数"<<endl;
    }

    void display() const
    {
        cout<<"m = "<<m<<endl;
        cout<<"n = " << n<<endl;
    }
private :
     int m , n;
};
int main()
{
   S const s(1,2);
   s.setvalue();
   s.display();
    return 0;

 

常引用       const 数据类型   &引用名=目标变量名; 

   例1
int a = 1 ;
const int &ra=a;
 当 ra=4;   a = 4;

对引用变量的改变就是对原变量的改变

 常对象的数据成员值在在对象整个生存期中是不能改变的;

 

C++

标签:

原文地址:http://www.cnblogs.com/webph/p/5544160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!