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

C++类中const一些用法

时间:2015-08-06 02:14:35      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:c++

在类中的const基本有三种用法

const int func(); // 返回值是const类型

int func(const int); // 参数为const类型

int func(int )const; // 为const类型的成员函数,只能调用类中const类型的变量;

另外,当类的实例是const类型时,也只能调用类中的const成员函数,且只有类的成员函数才能被修饰为const类型;

//Point.h
#include <iostream>
using namespace std;

class Point{
private:
    int x,y;

public:
    Point(int a,int b){
        x=a;y=b;
        cout<<"Point constructor is called !\n";
    };
    ~Point(){
    cout<<"Point destructor is called !\n";
    }
    
public:
    const int getX(){
        return x;
    }
    const int getY(){
        return y;
    }

public:
    void setX(const int a,int b) {
        x=a;y=b;
    }

public:
    void printPoint() const{
        cout<<"const type\n";
        cout<<"x="<<x<<",y="<<y<<endl;
    }
    void printPoint(){
        cout<<"non const type\n";
        cout<<"x="<<x<<",y="<<y<<endl;
    }
};
//main.cpp
#include <iostream>
#include "Point.h"
int main(int argc, const char * argv[])
{

    // insert code here...
    Point p(10,20);
    Point const p1(30,40);
    p1.printPoint();
    p.printPoint();
    //std::cout << "Hello, World!\n";
    return 0;
}

cout:

Point constructor is called !

Point constructor is called !

const type

x=30,y=40

not const type

x=10,y=20

Point destructor is called !

Point destructor is called !

Program ended with exit code: 0


将类中的

 void printPoint()

函数删除时则输出:

Point constructor is called !

Point constructor is called !

const type

x=30,y=40

const type

x=10,y=20

Point destructor is called !

Point destructor is called !

Program ended with exit code: 0


所以类中的非 const成员函数也可调用const类型成员函数。


本文出自 “c0c0s” 博客,请务必保留此出处http://9362125.blog.51cto.com/9352125/1682057

C++类中const一些用法

标签:c++

原文地址:http://9362125.blog.51cto.com/9352125/1682057

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