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()
    */

    
    
  • 相关阅读:
    命令行
    作业三C++
    作业二
    0003---简单的a+b问题
    0002---五层小山
    0001---Hello world
    关于OJ的那些事
    CDQ分治学习笔记
    C++ IO的一些注意点
    Vscode配置C++环境
  • 原文地址:https://www.cnblogs.com/mylinux/p/4091708.html
Copyright © 2011-2022 走看看