上嵌学习笔记

C++基础-(静态成员和友元)

2016-11-10  本文已影响11人  I踏雪寻梅

C++基础

静态成员和友元

#include <iostream>
using namespace std;
//+int num;使用全局变量
class Student
{   //-int num;
    static int num;
    int id;
    public:
        Student()
        {
    
            //-num=0;每执行一次Student都会重归为0,最后结果为1,1
            num++;
        }
        ~Student()
        {
            num--;
        }
        int getId()
        {
            id=0;
            return num;
        }   
        static int getNum()
        {
            //id=0;//在此处id为int类型,不能在此修饰.一个静态成员函数不与任何对象相联系,故不能对非静态成员进行默认访问。
            return num;
        }
};
int Student::num=0;//初始化一定要在外面
int main()
{
//  cout<<"student num0="<<Student::getNum()<<endl;
    Student t1;
    Student t2;
    Student *t3=new Student;
    cout<<"student num1="<<t1.getNum()<<endl;
    delete t3;
    cout<<"student num2="<<t1.getNum()<<endl;
//  cout<<"student num0="<<Student::getNum()<<endl;
}

友元

#include <iostream>
using namespace std;
class Student
{
    int m_id;
    public:
        Student(int id)
        {
            m_id=id;
        }
        friend void test(Student t);
};
void test(Student t)
{
    cout<<"id="<<t.m_id<<endl;//m_id是受保护的私有的,所以不用friend会出错。
}
int main()
{   
    Student t1(10);
    test(t1);
}
#include <iostream>
using namespace std;
class Student
{
    int m_id;
    public:
        Student(int id)
        {
            m_id=id;
        }
        friend class A;
};
class A
{
    public:
        void test(Student t)
        {
            cout<<"id="<<t.m_id<<endl;
        }
};
int main()
{   
    Student t1(10);
    A a;
    a.test(t1);
}
#include <iostream>
using namespace std;
class Student;
class A
{
    public:
        void test(Student t);
};
class Student
{
    int m_id;
    public:
        Student(int id)
        {
            m_id=id;
        }
        friend void A::test(Student t);
};
void A::test(Student t)
{
    cout<<"id="<<t.m_id<<endl;
}
int main()
{   
    Student t1(10);
    A a;
    a.test(t1);
}
class S
{
    friend B;
    //friend B;
    //friend A;//可过
}
Class B
{
    friend A;
    
}
class A
{}
上一篇下一篇

猜你喜欢

热点阅读