在2个cpp文件中定义一个C++类
Define a C++ class in 2 cpp files?
我是否可以在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!
只有这个!
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '