C++ 封装 随笔

来源:互联网 发布:扒谱子软件 编辑:程序博客网 时间:2024/06/05 00:14
【同文件类内定义】
#include <iostream>#include <string>using namespace std;/**  * 定义类:Student  * 数据成员:m_strName  * 数据成员的封装函数:setName()、getName()  */class Student{public:    // 定义数据成员封装函数setName()      void setName(string a)      {          m_strName=a;      }            // 定义数据成员封装函数getName()     string getName()     {         return m_strName;     }    //定义Student类私有数据成员m_strNameprivate:  string m_strName;};int main(){    // 使用new关键字,实例化对象Student *str = new Student;    // 设置对象的数据成员str->setName("hello world");    // 使用cout打印对象str的数据成员       cout<<str->getName();    // 将对象str的内存释放,并将其置空   delete str;   str=NULL; return 0;}



【同文件类外定义】

#include <iostream>#include <string>using namespace std;/**  * 定义类:Student  * 数据成员:m_strName  * 数据成员的封装函数:setName()、getName()  */class Student{public:    // 定义数据成员封装函数setName()      void setName(string a);                  // 定义数据成员封装函数getName()     string getName();     //定义Student类私有数据成员m_strNameprivate:  string m_strName;};// 外部编写函数setName()void Student::setName(string a)      {          m_strName=a;      }// 外部编写函数getName()     string Student::getName()     {         return m_strName;     }    int main(){          // 使用new关键字,实例化对象Student *str = new Student;    // 设置对象的数据成员str->setName("hello world");    // 使用cout打印对象str的数据成员       cout<<str->getName();    // 将对象str的内存释放,并将其置空   delete str;str=NULL;return 0;}

【分文件类外定义】

要创建 Student.h文件

文件内容:

class Student{public:    // 定义数据成员封装函数setName()      void setName(string a);                  // 定义数据成员封装函数getName()     string getName();     //定义Student类私有数据成员m_strNameprivate:  string m_strName;};cpp文件使用时,要声明  #include"Student.h"