#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string _name;
int _age;
public:
//构造函数
Student()
{
_name = "";
_age = 0;
}
Student(string name, int age)
{
_name = name;
_age = age;
}
//析构函数
~Student()
{
_name = "";
_age = 0;
}
//公有方法
void SetName(string name){_name=name;}
string GetName()const{return _name;}
void SetAge(int);
int GetAge()const;
};
//在类外定义方法
inline void Student::SetAge(int age)
{
_age = age;
}
inline int Student::GetAge()const
{
return _age;
}调用示例:
#include <iostream>
#include "cls.h"
using namespace std;
int main()
{
Student stu("zhang",29);
cout<<"Name:"<<stu.GetName()<<endl;
cout<<"Age:"<<stu.GetAge()<<endl;
return 0;
}与C#类比较,C++的类有如下特点:
·公有成员和私有成员明显分开;
·类属性没有set和get访问器;
·公有成员允许在类定义的外面进行定义;
·类结束需要一个分号;
·inline关键字表示该函数是一个内联函数;
·const关键字表示该成员函数内不会修改任何成员变量;
·创建类实例时不需要使用new关键字;
评论(0)
暂无评论。