//student.cpp
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文件
示例如下:
//student.cpp #include#include "student.cpp" using namespace std; int main() { student S; double age = S.getDoubleAge(15); cout< 方法二:直接在头文件中写声明和定义(不推荐)
//student.h #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文件里写定义(标准写法)
//student.h #ifndef STUDENT_H #define STUDENT_H class student { private: public: student(); ~student(); double getDoubleAge(double age); }; #endif//student.cpp #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}", //在这里添加需要编译的cpp文件 "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 } } ] }为什么不直接把声明和定义都写在头文件?其目的就是解耦,让各个模块功能独立,同时提高编译速度;如果将全部代码都写在一个文件里,那么会导致程序高耦合,代码阅读性差,编译速度慢,引用困难。解耦是一种设计思想。



