在2个cpp文件中定义一个C++类

Define a C++ class in 2 cpp files?

本文关键字:一个 C++ cpp 2个 文件 定义      更新时间:2023-10-16

我是否可以在1个头文件中声明我的类,并在2个分开的cpp文件中定义(像C#中一样)
主要原因是我减少了我现在拥有的单个文件中类定义的行数。顺便说一句,我所有的标题都是"include guarded"+"pragma onced"。

标题:"foo.h"

#pragma once
#ifndef FOO_H_2014_04_15_0941
#define FOO_H_2014_04_15_0941
class CFoo
{
public:
    int add(int a, int b);
    int sub(int a, int b);
};
#endif

来源:"foo.cpp"

#include "stadafx.h"
#include "foo.h"
int CFoo::add(int a, int b)
{
    return a + b;
}

"foo2.cpp"

#include "stadafx.h"
#include "foo.h"
int CFoo::sub(int a, int b)
{
    return a - b;
}

当我尝试时,在第二个cpp文件"cannot open source file stdafx.h"(也称为"foo.h")中出现编译器错误

是的,你可以这样做。

stdafx.h是一个预编译的头文件。这是Visual Studio的惯例。为了优化编译,经常使用的头被放在stdafx.h中,然后包含这个文件。问题是必须#include "stdafx.h"放在源文件的顶部。

您可以执行此操作,也可以禁用此.cpp文件的预编译头使用。或者你的整个项目。

确保在foo.h文件中也使用include保护。要么是@Theolodis所说的一系列预处理器指令,要么是#pragma once


我同意@paulm的观点:像这样拆分你的实现只是表明你的设计有缺陷。这是一个"正确"的决定,这是非常罕见的。很可能您应该考虑将代码分解为更小、更易于管理的组件。

在标题中添加:

#ifndef FOO_H_
#define FOO_H_
class CFoo
{
public:
    int add(int a, int b);
    int sub(int a, int b);
}
#endif

问题是头文件在可执行文件中包含了两次,导致名称冲突。否则一切都很好,您甚至可以为每个方法获取一个.cpp文件。

首先,不要在同一个头文件中使用"include-guard"answers"pragmaonced"!仅使用"包含防护"!

其次,你必须在windows上开发,可以使用visualstudio。因为您使用了预编译的头文件:stdafx.h,并且拼写为ERROR!

只有这个!