在静态成员函数中访问非静态成员变量

在静态成员函数中访问非静态成员变量

在正常情况下一个static修饰的静态成员函数是无法对非静态成员变量进行访问与操作的 :

#include <iostream>
using namespace std;

class Date
{
public :
    Date(int y = 1998, int m = 2, int d = 15)
        :year(y)
        ,month(m)
        //,day(d)
    {
        day = 16;
    }

    static void Print()
    {
        cout << "this is the static function ..." << "day :" << day <<"unstatic : "<<year<< endl;
    }

    friend ostream& operator<<(const Date&, ostream&);//

private :
    int year;
    int month;
    static int day;
};

int Date::day = 14;

ostream& operator<<(const Date& d, ostream& os)
{
    os << d.year << " " << d.month << " " << d.day;
    return os;
}

int main()
{
    Date d1;
    d1.Print();
    //d1<<cout;
    return 0;
}

编译结果发生错误,无法编译成功,证明一般情况下无法访问


在特殊情况下可以通过在静态成员函数参数列表中传递类的地址来实现对类对象的非静态成员变量进行访问与操作

#include <iostream>
using namespace std;

class Date
{
public :
    Date(int y = 1998, int m = 2, int d = 15)
        :year(y)
        ,month(m)
        //,day(d)
    {
        day = 16;
    }

    static void Print(Date* A) //静态成员函数
    {
        cout << "per " << *A << endl;
        A->Add();
        cout << "after" << *A << endl;
    }

    friend ostream& operator<<(ostream&, const Date&);//
    void Add()
    {
        year++;
        month++;
        day++;
    }

private :
    int year;
    int month;
    static int day;
};

int Date::day = 14;

ostream& operator<<(ostream& os,const Date& d)
{
    os << d.year << " " << d.month << " " << d.day;
    return os;
}

int main()
{
    Date d1;
    d1.Print(&d1);
    return 0;
}

运行结果 :
这里写图片描述
通过这样的方式就能实现静态成员函数对非静态成员变量进行访问了…

猜你喜欢

转载自blog.csdn.net/liu_zhen_kai/article/details/81274241
今日推荐