Bit*_*lue 1 c++ oop visual-c++
我可以在1个头文件中声明我的类并在2个独立的cpp文件中定义它吗?(就像在C#中一样)
主要原因是我在现在的单个文件中减少了我的类定义的行数.顺便说一句,我所有的标题都是"包括守卫"+"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
Run Code Online (Sandbox Code Playgroud)
资源: "foo.cpp"
#include "stadafx.h"
#include "foo.h"
int CFoo::add(int a, int b)
{
return a + b;
}
Run Code Online (Sandbox Code Playgroud)
和 "foo2.cpp"
#include "stadafx.h"
#include "foo.h"
int CFoo::sub(int a, int b)
{
return a - b;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在第二个cpp文件中得到编译器错误"无法打开源文件stdafx.h"(也是"foo.h")
是的,你可以这样做.
stdafx.h是一个预编译的头文件.这是Visual Studio的约定.为了优化编译,经常使用的标题放入stdafx.h,然后包含此文件.问题是您必须放在#include "stdafx.h"源文件的顶部.
您可以执行此操作,也可以禁用此.cpp文件的预编译标头使用情况.或者整个项目.
确保在foo.h文件中也使用包含警戒.要么是@Theolodis所说的一系列预处理程序指令,要么是#pragma once.
我同意@paulm:像这样拆分你的实现只是表明你的设计存在缺陷.这是非常非常罕见的,这是"正确"的决定.您最有可能考虑将代码分解为更小,更易于管理的组件.