C++的类

C++类示例(cls.h):
#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关键字;

上一篇: C++的内联函数
下一篇: 风雨20年:我所积累的20条编程经验
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
最新日志:
评论: 0 | 引用: 0 | 查看次数: 3594
发表评论
登录后再发表评论!