C++ 封装

  • Teacher.h
#include <string>
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 <iostream>
#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 <string>
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 <iostream>
#include "Teacher.h"

using namespace std;

const int height = 180;

Teacher::Teacher(string str,int i)
{
    name = str;
    age = i;
    cout << "类被创建了"<<endl;
}

Teacher::~Teacher()
{
    cout << "类被销毁了"<<endl;
}

void Teacher::setName(string str)
{
    name = str;
}
    
string Teacher::getName()
{
    return name;
}

int Teacher::getAge()
{
    return age;
}

int Teacher::getConstHeight()
{
    return height;
}
#include <iostream>
#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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。