C++ 头文件 源程序 类实战

本文通过一个简单的C++学生类实例,展示了如何使用私有成员变量进行数据封装,并提供了公共成员函数来设置和获取这些变量。同时介绍了如何创建头文件和源文件,并在主程序中调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般情况下 一个头文件  一个源程序   同名    源程序include进来头文件 

Student.h

#include<iostream>
#include<string>
using namespace std;
class Student {
public:
//把私有的类内成员变量封装起来
void setName(string name);
string getName();
void setAge(int age);
int getAge();
void study();
private:
string m_strName;
int m_iAge;       //定义两个私有的成员变量
};


Student.cpp

#include"Student.h"
void Student::setName(string name)
{
m_strName = name;
}
string Student::getName()
{
return m_strName;
}
void Student::setAge(int age)
{
m_iAge = age;
}
int Student::getAge()
{
return m_iAge;
}
void Student::study() {
cout << "study" << endl;
}


主程序:

#include<iostream>
#include"Student.h"
using namespace std;
int main() {
Student stu;
stu.setName("join");
stu.setAge(20);
cout<<stu.getName() << "  " << stu.getAge() << endl;
stu.study();
system("pause");
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值