zoukankan      html  css  js  c++  java
  • 随便写一个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
    请按任意键继续. . .
  • 相关阅读:
    【BUUCTF】WEB SECRET FILE
    你是如何让函数返回IEnumerable<T>的
    对Closure的再思考
    旋转的女郎
    Tools in Visual Studio 2010
    解析命令行的正则表达式
    Closure中关于递归的一点补充
    对C++和C#中多态及类型转换的理解(二)
    对C#和C++0x中Lamda表达式的简略对比
    对C++和C#中多态及类型转换的理解(一)
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/12013501.html
Copyright © 2011-2022 走看看