我收到编译错误:
错误7错误C2084:函数'Boolean IsPointInRect(...)'已经有一个正文
在我的内联函数中,在cpp文件中声明如下:
inline Boolean IsPointInRect(...)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我在另一个cpp文件中具有完全相同的功能.可能这会导致问题吗?我怎么解决呢?
Geo*_*che 14
正如litb和AndreyT指出的那样,这个答案并没有解决实际问题 - 详见litbs答案.
虽然static,作为奥菲尔说,为您提供了内部联动,"C++的方式"是使用未命名空间:
namespace
{
inline Boolean IsPointInRect(/*...*/) { /*...*/ }
}
Run Code Online (Sandbox Code Playgroud)
§7.3.1.1/ 1:
未命名的命名空间定义的行为就像被替换为
namespace unique { /* empty body */ }
using namespace unique;
namespace unique { namespace-body }
Run Code Online (Sandbox Code Playgroud)
其中翻译单元中所有唯一的出现都被相同的标识符替换,并且该标识符与整个程序中的所有其他标识符不同.
§7.3.1.1/ 2补充说:
在声明命名空间范围内的对象时,不推荐使用static关键字(见附录D); unnamed-namespace提供了一个更好的选择.
Joh*_*itb 10
你在这个帖子中得到了一些错误的答案.您的代码中的问题是您在代码中定义了两次内联函数:
inline Boolean IsPointInRect(...) { ... }
inline Boolean IsPointInRect(...) { ... }
Run Code Online (Sandbox Code Playgroud)
inline将正如其他人所说的那样,通过两次定义函数,已经保护您不会出现错误.您不需要static,也不需要未命名的命名空间.另请注意,您不应该定义应该由文件中的其他翻译单元(处理和扩展所有#include和#if等...的.cpp文件)使用的内联函数.所有使用它们的翻译单元都必须知道它们的定义 - 所以在这种情况下只将它们的定义放在头文件中 - 而不是在.cpp头文件和头文件中 - 这将导致你得到的错误.
您还需要标头防护,以避免每个标头中出现上述问题
// file foo.h
#ifndef POINTS_H_INCLUDED
#define POINTS_H_INCLUDED
inline Boolean IsPointInRect(...) { ... }
#endif
// file bar.cpp
#include "foo.h"
// does not include the content a second time anymore - the guards aboid it:
#include "foo.h"
Run Code Online (Sandbox Code Playgroud)
并且您应确保不将.cpp文件包含到另一个.cpp文件中(.cpp不应包含文件).您应该将头文件包含在.cpp文件中.
| 归档时间: |
|
| 查看次数: |
3903 次 |
| 最近记录: |