作者: const_qiu | 来源:发表于2020-09-17 15:05 被阅读0次
    • this指针的类型:class_type* const ,即this的值不可以修改,但是this指向的对象的数据可以修改。
      this 不能绑定到一个常量对象上,所以不能在常量对象上调用普通的成员函数(隐式传入this指针)
      比如:
    #include <iostream>
    using namespace std;
    class Base {
     public:
         void print_test() {
             cout << "hhhh" << endl;
         }
    };
    
    int main()
    {
        Base const s ;
        s.print_test(); //会报错,print_test()不是常成员函数,
    }
    
    • 当类内定义了带参数的构造函数,那么编译器就不会为类生成默认构造函数,如果此时还想用默认构造函数,就要自己定义一个。
    • 友元函数:

    在类中把某个函数声明为friend,既可以是private也可以是public

    friend 函数破坏了类的封装:

    class Base {
     public:
         Base( ) {
             cout << "create a object" << endl;
         }
    public:
         friend void test_friend(Base& );
    private:
        int base_a = 0; 
    };
    void test_friend(Base& b) {
        cout << "我是友元函数" <<b.base_a<< endl;
    }
    
    int main()
    {
        Base  s;
        test_friend(s);
    }
    

    相关文章

      网友评论

          本文标题:

          本文链接:https://www.haomeiwen.com/subject/owuesktx.html