随便写一个c++类

为了让代码更贴合实际项目需要,我们分别用xxx.h文件,xxx.cpp文件来包含类的定义,类的声明和类的调用部分,实验平台vs2010

  • mycoach.h文件
#pragma once
#include<iostream>
#include<string>
using namespace std;
class mycoach
{
private:
    string name;
    int age;
    string favorite;
public:
    mycoach(string name,int age);
    mycoach(const mycoach &p);
    //void setid(string name,int age);
    string getname()
    {
        return name;
    }
    int getage()
    {
        return age;
    }
    ~mycoach(void);
    
    
    void selfintroduce() const //const用来限制成员函数,保证成员不被修改,可以根据实际需要去掉
    {
        cout<<"hello~ i.m "<<name<<endl;
        cout<<this->age<<"years old"<<endl;
    }
    
    void setid(string name,int age)//之所以放到这里是因为,如果放到定义文件中,就识别不了类对象指针this了,十分蛋疼,selfintroduce也是一样
    {
        this->name=name;
        this->age=age;
    }

};
  • mycoach.cpp文件
#include "mycoach.h"
#include<iostream>
#include<string.h>
using namespace std;

mycoach::mycoach(string name,int age)
{
    name=name;
    age=age;
}

mycoach::mycoach(const mycoach &p)
{
    name=p.name;
    age=p.age;
}


mycoach::~mycoach(void)
{
}
  • main()函数
#include<iostream>
#include<string.h>
#include "mycoach.h"
using namespace std;
void main()
{
    mycoach coach1("陈培昌",22);
    mycoach coach2(coach1);//这里用到了拷贝构造函数
    coach2.setid("付高峰",30);
    coach2.selfintroduce();
    system("pause");
}

实验结果:

hello~ i.m 付高峰
30years old
请按任意键继续. . .

猜你喜欢

转载自www.cnblogs.com/saintdingspage/p/12013501.html