zoukankan      html  css  js  c++  java
  • C++,常成员函数

    #include <iostream>
    using namespace std;
    
    class Test {
    public:
        int x;
        int y;
        void const_m1() const;
        void const_m2() const;
        void m3();
        void m4();
    };
    /**
     * //1常成员函数不能修改成员变量的值
     * //2常成员函数只能调用常成员函数,不能调用普通成员函数
     * //3普通成员函数可以调用常成员函数
     */
    void Test::const_m1(void)const {
        cout<<"start of const_m1() ,call:"<<endl;
        this->const_m2();//可以调用const_m2()
        //this->m3();//error C2662: “Test::m3”: 不能将“this”指针从“const Test”转换为“Test &”
        //this->m4();//error C2662: “Test::m4”: 不能将“this”指针从“const Test”转换为“Test &”
        //this->x = 3;//error C3490: 由于正在通过常量对象访问“x”,因此无法对其进行修改
        cout<<"end of const_m1()"<<endl;
    }
    void Test::const_m2(void)const {
        cout<<"this is const_m2()"<<endl;
    }
    void Test::m3(void) {
        cout<<"this is m3(),call:"<<endl;
        this->const_m2();
        cout<<"end of m3()"<<endl;
    }
    void Test::m4(void) {
        cout<<"this is m4()"<<endl;
        this->x = 3;
    }
    
    int main(void) {
        Test demo;
        demo.const_m1();
        demo.const_m2();
        demo.m3();
        demo.m4();
        while(1);
        return 0;
    }

    /*测试结果:
    start of const_m1() ,call:
    this is const_m2()
    end of const_m1()
    this is const_m2()
    this is m3(),call:
    this is const_m2()
    end of m3()
    this is m4()
    */

    
    
  • 相关阅读:
    一个星期自动态的网站设计
    java特权制度设计篇
    mac默认截图、截图代码
    NSDateFormatter
    vlan 以及 Linux实现的IEEE 802.1Q VLAN
    gtk+blade+anjuta 的简单实例
    NetBSD是个开源到源码的系统
    创作gtk源码级vim帮助文档 tags
    linux 怎么使用一个c/c++库
    linux 终端控制-- 多彩输出 格式排版
  • 原文地址:https://www.cnblogs.com/mylinux/p/4091708.html
Copyright © 2011-2022 走看看