一个类的声明
class student
{
private:
public:
double getDoubleAge(double age);
student();
~student();
};
student::student(){}
student::~student(){}
double student::getDoubleAge(double age)
{
return age*2;
}
若要在其他cpp文件中调用这个类
方法一:直接调用cpp文件 头文件声明中直接添加需要调用的类的cpp文件 示例如下:
#include <iostream>
#include "student.cpp"
using namespace std;
int main()
{
student S;
double age = S.getDoubleAge(15);
cout<<age<<endl;
return 0;
}
方法二:直接在头文件中写声明和定义(不推荐)
#ifndef STUDENT_H
#define STUDENT_H
class student
{
private:
public:
student();
~student();
double getDoubleAge(double age);
};
student::student(){}
student::~student(){}
double student::getDoubleAge(double age)
{
return age*2;
}
#endif
方法三:头文件里写声明,cpp文件里写定义(标准写法)
#ifndef STUDENT_H
#define STUDENT_H
class student
{
private:
public:
student();
~student();
double getDoubleAge(double age);
};
#endif
#include "student.h"
student::student(){}
student::~student(){}
double student::getDoubleAge(double age)
{
return age*2;
}
注意事项
vscode和vs的编译逻辑不同,vs会把整个目录下的cpp都编译,但是vscode不会,所以使用vscode调用其他类时,要在task.json中添加需要编译的cpp文件,以本篇文章为例,则:
{
"version": "2.0.0",
"tasks": [{
"label": "g++",
"command": "g++",
"args": [
"-g",
"${file}",
"F:\\Thunderdowm\\Learning\\c++\\student.cpp",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"problemMatcher": {
"owner": "cpp",
"fileLocation": [
"relative",
"${workspaceRoot}"
],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
为什么不直接把声明和定义都写在头文件?
其目的就是解耦,让各个模块功能独立,同时提高编译速度;如果将全部代码都写在一个文件里,那么会导致程序高耦合,代码阅读性差,编译速度慢,引用困难。解耦是一种设计思想。
|