C++ 封装

  • Teacher.h
#include 
using namespace std;

class Teacher
{
private:
    string name;
   
public:
    void setName(string str);
    string getName();
};
  • Teacher.cpp
#include "Teacher.h"

using namespace std;

void Teacher::setName(string str)
{
    name = str;
}
    
string Teacher::getName()
{
    return name;
}
  • 初始化Teacher类
#include 
#include "Teacher.h"

using namespace std;

int main(int argc, const char * argv[]) {
    
    Teacher *teacher = new Teacher();
    teacher->setName("Roy");
    cout << teacher->getName() << endl;
    
    return 0;
}
  • 构造函数 和 析构函数
#include 
using namespace std;

class Teacher
{
private:
    string name;
    int age;
    
public:
    
    Teacher(string str,int age); // 构造函数
    ~Teacher(); // 析构函数
    
    void setName(string str);
    void setAge(int age);
    
    string getName();
    int getAge();
    int getConstHeight();
};
#include 
#include "Teacher.h"

using namespace std;

const int height = 180;

Teacher::Teacher(string str,int i)
{
    name = str;
    age = i;
    cout << "类被创建了"<
#include 
#include "Teacher.h"

using namespace std;

int main(int argc, const char * argv[]) {
    
    Teacher *t = new Teacher("WL",18); // 类被创建了
    cout << "名字: " + t->getName() << endl; // 名字: WL
    cout << "年龄: " <<  t->getAge() << endl; // 年龄: 18
    cout << "常量: " <<  t->getConstHeight() << endl; // 常量: 180
    
    delete t; // 类被销毁了
    t = NULL;
    
    return 0;
}

你可能感兴趣的:(C++ 封装)