关于指针的引用的讲解

来源:互联网 发布:淘宝开通直播间 编辑:程序博客网 时间:2024/04/29 19:52

前一段时间,一直纠结指针的引用,因为在关于二叉树的的一些操作中需要用到指针的引用。具体就不讲了,现在主要写传入指针的引用与传入指针的区别。

假设我想实现一个管理员的功能,管理学生信息,无法访问到学生的指针(比如说有了学生的指针,管理员就可以看到很多学生的隐私),只能访问到学生内部的指针(比如教师的指针,为了简单,这里假设学生只有一个指针)。

#include <iostream>
#include <string>
using namespace std;
class Teacher{
    string name;
    int id;
    string phone;
public:
    Teacher(string name, int id, string phone){
        this->name = name;
        this->id = id;
        this->phone = phone;
    }
    string getName( ){
        return name;
    }
    int getId( ){
        return id;
    }
    string getPhone( ){
        return this->phone;
    }
    void setName(string name){
        this->name = name;
    }
    void setId(int id)
    {
        this->id = id;
    }
    void setPhone(string phone){
        this->phone = phone;
    }
    void display( ){
        cout << "Teacher:" << this->name << "-id:" << this->id << "-phone:" << this->phone << endl;
    }


};
class Student{
    string name;
    int id;
    Teacher * teacher;
public:
    //给某个学生的teacher初始化一个教师,传入的参数tea应该默认为NULL
    /*
    注意,这里一定要用指针的引用,
    这里传入的参数是对学生的teacher指针域的引用,
    如果不传入指针的引用,修改的是内存中另一个指针的值,
    而不是学生对应teacher的值
    */
    static void AddStuTea(Teacher*&tea,string name,int id,string phone){
        tea = new Teacher(name, id, phone);
    }
    /*   //下面这个只能修改形参,student中的tea还是NULL,调用下面的函数会导致错误结果
    static void AddStuTea(Teacher*tea, string name, int id, string phone){
        tea = new Teacher(name, id, phone);
    }
    */
    //这里是设置一个学生的教师的信息,传入的是学生教师的指针,不需要指针的引用
    //因为这里修改的不是指针的值,而是指针指向的那块内存的值
    //因为形参和实参指向的都是同一块内存
    static void SetTeaInfo(Teacher* tea, string name, int id, string phone){
        tea->setName(name);
        tea->setId(id);
        tea->setPhone(phone);
    }


    Student(string name, int id, Teacher* teacher){
        this->name = name;
        this->id = id;
        this->teacher = teacher;
    }
    Student( ){
        this->name = "";
        this->id = -1;
        this->teacher = NULL;
    }
    string getName( ){
        return name;
    }
    int getId( ){
        return id;
    }
    Teacher*& getTeacher( ){
        return this->teacher;
    }
    void setName(string name){
        this->name = name;
    }
    void setId(int id)
    {
        this->id = id;
    }
    void setTeacher(Teacher* teacher){
        this->teacher = teacher;
    }
    void display( ){
        cout << this->name << ":" << this->id << endl;
        this->teacher->display( );
    }
};

int main( ){
    Student* s = new Student("wang", 201392252, NULL);

Teacher* t = s->getTeacher( );

   Student::SetTeaInfo(t,"www",666666,"18888888888");
    s->display( );

//一定要是传入引用,不能指针
    Student::AddStuTea(s->getTeacher( ),"sss",123456,"123456789");
    s->display( );
    return 0;
}

附图解释

0 0