C++学习 - 面向对象 - 面向对象的语法特性(1)


类的概念

定义一个类Human,包含Name \ Age 两个属性,构造函数和析构函数,还有一个introduceSelf的方法

Human.h

#ifndef HUMAN_H
#define HUMAN_H

#include 
#include 

using namespace std;

class Human
{
    public:
        Human();
        virtual ~Human();
        void setAge(int age);
        int getAge();

        void setName(string name);
        string getName();

        void introduceSelf();
    protected:
    private:
        string m_strName;
        int m_iAge;
};

#endif // HUMAN_H

Human.cpp

#include "Human.h"

Human::Human()
{
    m_iAge    = 0;
    cout << "Human::Human" << endl;
}

Human::~Human()
{
    cout << "Human::~Human" << endl;
}

void Human::setAge(int age)
{
    m_iAge = age;
}

int Human::getAge()
{
    return m_iAge;
}

void Human::setName(string name)
{
    m_strName = name;
}

string Human::getName()
{
    return m_strName;
}

void Human::introduceSelf()
{
    cout << "m_iAge = " << m_iAge << endl;
    cout << "m_strName = " << m_strName << endl;
}

main.cpp

#include "Human.h"

int main(int argc, char** argv)
{
    Human p1;
    Human p2;

    p1.setAge(10);
    p1.setName("lilei");

    p2.setAge(20);
    p2.setName("jim");

    p1.introduceSelf();
    p2.introduceSelf();
    return 0;
}

执行测试:

C++学习 - 面向对象 - 面向对象的语法特性(1)_第1张图片
image.png

你可能感兴趣的:(C++学习 - 面向对象 - 面向对象的语法特性(1))