zoukankan      html  css  js  c++  java
  • C++ Error C2662 cannot convert 'this' pointer from 'const *'

    ---恢复内容开始---

    这个错误在于一点:常量对象只能调用常量成员(函数变量),不能调用非常量成员。另一方面,非常量对象,既可以调用常量成员,又可以调用非常量成员。

     class A {
     public:
    	 void fun_1() {
    		 std::cout << "非常量函数" << std::endl;
    	 }
    	 
    	 void fun_2() const {
    		 std::cout << "非常量函数" << std::endl;
    	 }
    
     };
     
     int main() {
    	 
    	 const A a;
    	 a.fun_1();//编译报错,
             a.fun_2();//编译通过
     }
    

    上面这个简单得代码,可以说明这个问题。

    对于实例化对象a, 被定义为常量对象,因此可以调用调用fun_2(), 不能调用fun_1()

    在C++当中,我们在函数参数后面加上const,如上面代码fun_2()那样,则将整个成员变成常量成员,即将*this, 转换成const *this.

  • 相关阅读:
    mysql常用技能分享
    php生成器使用总结
    MySQL索引使用方法和性能优化
    servlet相关
    UML图
    How Tomcat Works
    字符串编码
    高效工作
    php 设计模式总结
    python之装饰器
  • 原文地址:https://www.cnblogs.com/code-wangjun/p/9037198.html
Copyright © 2011-2022 走看看