栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

vscode不同cpp文件中类的调用(C++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

vscode不同cpp文件中类的调用(C++)

一个类的声明
//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
            }
        }
    ]
}
为什么不直接把声明和定义都写在头文件?

其目的就是解耦,让各个模块功能独立,同时提高编译速度;如果将全部代码都写在一个文件里,那么会导致程序高耦合,代码阅读性差,编译速度慢,引用困难。解耦是一种设计思想。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/311955.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号