zoukankan      html  css  js  c++  java
  • [C++基础]C++中静态成员函数如何访问非静态成员

    #include <iostream>
    /*
    静态成员函数只能访问静态数据成员、静态成员函数和类以外的函数和数据,不能访问非静态数据成员,但静态成员函数或静态数据成员可由任意访问许可的函数访问。原因是:当前对象的地址(this)是被隐含地传递到被调用的函数的。但一个静态成员函数没有this指针,所以它无法访问非静态的成员函数。
    */
    class a
    {
    public:
        static void FunctionA()//静态成员函数没有隐含的this自变量
        {
            //menber = 1;//error C2597:对非静态成员"a::member"的非法引用
            //printValue();//error C2352:“a::printValue”:非静态成员函数的非法调用
        }
        void printValue()
        {
            printf("menber=%d
    ",menber);
        }
    private:
        int menber;
    };
    /*如何访问非静态成员呢?
    1.把非静态成员修改成静态成员。如:static int member;//这就不会出错了,但有些不妥
    2.将对象作为参数,通过对象名来访问该对象的非静态成员
    */
    class A
    {
    public:
        A():menber(10){}
        static void FunA(A& _A)
        {
             _A.menber = 123;
             _A.printValue();
        }
        static void FunB(A* _A)
        {
            _A->menber = 888;
            _A->printValue();
        }
        void printValue()
        {
            printf("menber=%d
    ",menber);
        }
    private:
        int menber;
    };
    int _tmain(int argc, _TCHAR* argv[])
    {
        A* m=new A();
        m->FunB(m);
        A::FunB(m);
        A::FunA(*m);
    
        A b; 
        b.FunA(b);
        A::FunB(&b);
        b.FunB(&b);
        m->FunB(&b);
        return 0;
    }


  • 相关阅读:
    前沿科技相关
    52ABP
    C#常用及注意点
    电商秒杀系统:电商微服务框架组件
    面向对象OOP
    《CLR via C#》书籍
    .NET发布时选择【独立部署模式】引发的故事
    unity 3D物体使用EventSystem响应事件
    协程
    unity 2d碰撞/ui组件碰撞
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3285803.html
Copyright © 2011-2022 走看看