标签:
对象的使用
对象指针:
当定义对象指针后,可以利用对象指针访问其指向的对象的公有成员,语法形式:
对象指针->公有成员;
对象引用:
Student stu(1,”wang”,’M’);
Student rstu=stu;
它是一种特殊的指针,它指向员函数当前操作的数据所属对象。
与普通变量做函数参数一样。
例子:
#include<iostream> #include<cstring> using namespace std; class Student{ public: Student(int pId,char* pName,char pSex); int getId(){ return id; } char* getName(){ return name; } char getSex(){ return sex; } private: // public: int id; char* name; char sex; }; Student::Student(int pId,char* pName,char pSex) { id=pId; name=new char[strlen(pName)+1]; if(name!=0) strcpy(name,pName); sex=pSex; } class Admin{ public: Admin(int pId); void printStudent(Student stu); private: int id; }; Admin::Admin(int pId) { id=pId; } void Admin::printStudent(Student stu) { cout<<"The student information is: "<<"id: "<<stu.getId()<<","<<"name: "<<stu.getName()<<","<<"sex: "<<stu.getSex()<<endl; // cout<<"The student information is: "<<"id: "<<stu.id<<","<<"name: "<<stu.name<<","<<"sex: "<<stu.sex<<endl; } int main() { Student stu(1,"wang",'M'); Admin admin(11);//为什么? admin.printStudent(stu); return 0; }
与普通变量指针做函数参数的用法一样。
#include<iostream> #include<cstring> using namespace std; class Student{ public: Student(int pId,char* pName,char pSex); int getId(){ return id; } char* getName(){ return name; } char getSex(){ return sex; } void setId(int pId) { id=pId; } void setName(char* pName) { name=new char[strlen(pName)+1]; if(name!=0) strcpy(name,pName); } void setSex(char pSex){sex=pSex;} private: // public: int id; char* name; char sex; }; Student::Student(int pId,char* pName,char pSex) { id=pId; name=new char[strlen(pName)+1]; if(name!=0) strcpy(name,pName); sex=pSex; } class Admin{ public: Admin(int pId); void printStudent(Student stu); void updateStudent(Student* pStu,int pId); void updateStudent(Student* pStu,char* pName); void updateStudent(Student* pStu,char pSex); private: int id; }; Admin::Admin(int pId) { id=pId; } void Admin::printStudent(Student stu) { cout<<"The student information is: "<<"id: "<<stu.getId()<<","<<"name: "<<stu.getName()<<","<<"sex: "<<stu.getSex()<<endl; } void Admin::updateStudent(Student* pStu,int pId) { pStu->setId(pId); } void Admin::updateStudent(Student* pStu,char* pName) { pStu->setName(pName); } void Admin::updateStudent(Student* pStu,char pSex) { pStu->setSex(pSex); } int main() { Student stu(1,"wang",'M'); Admin admin(91); admin.printStudent(stu); Student* pStu=&stu; admin.updateStudent(pStu,99); admin.printStudent(stu); admin.updateStudent(pStu,"zhao"); admin.printStudent(stu); admin.updateStudent(pStu,'F'); admin.printStudent(stu); return 0; }
与普通变量做函数参数的用法一样。
标签:
原文地址:http://blog.csdn.net/l15738519366/article/details/51333203