liming19680104

类的声明一般放在头文件中(xx.h),类的实现一般放在源文件中(xx.cpp) 

注意:在VS中,要通过 项目-->类  来添加  或右击工程--添加 ;

    不能创建文件,另存为,这样是错误的 

 

Student.h文件:

#include <iostream>
using namespace std;

class Student  //类的声明
    //包括函数的声明,成员的声明
{
public:
    Student(const string& name, int age, int no);//构造函数的声明
    void who(void);  //自定义函数的声明

private:
    string m_name;
    int m_age;
    int m_no;

};

 

Student.cpp文件

#include "Student.h"  //导入自己的头文件,Student.h是头文件名
using namespace std;

Student::Student(const string& name, int age, int no) {  //类函数的实行
    //注意在函数名前面加上 类名:: ,声明它的作用域
    //如果不加类名::,它就不是类函数了,是全局函数了
    cout << "执行构造函数了" << endl;
    m_name = name;
    m_age = age;
    m_no = no;

}

void Student::who(void) {
    cout << "我的名字是:" << m_name << endl;
    cout << "我的年龄是:" << m_age << endl;
    cout << "我的学号是:" << m_no << endl;
}

 

main文件:

#include <iostream>
#include "Student.h"

using namespace std;

int main()
{
    Student s("张三", 25, 10010);
    s.who();
}

 

 

 

 

分类:

技术点:

相关文章:

  • 2022-01-18
  • 2021-05-02
  • 2021-12-31
  • 2022-02-28
  • 2021-11-17
  • 2021-08-16
  • 2021-04-06
  • 2021-06-25
猜你喜欢
  • 2021-12-03
  • 2021-08-30
  • 2021-11-27
  • 2021-04-01
  • 2022-12-23
相关资源
相似解决方案