【发布时间】:2008-10-17 12:57:19
【问题描述】:
我有一个包含类的 c++ 头文件。 我想在几个项目中使用这个类,但我不想为它创建一个单独的库,所以我将方法声明和定义都放在头文件中:
// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{
class TestClass{
public:
void testMethod();
};
void TestClass::testMethod(){
// some code here...
}
} // end namespace test_ns
#endif
如果在同一个项目中我从多个 cpp 文件中包含此标头,我会收到一条错误消息“multiple definition of test_ns::TestClass::testMethod()”,而如果我将方法定义放在类主体中,则不会发生这种情况:
// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{
class TestClass{
public:
void testMethod(){
// some code here...
}
};
} // end namespace test_ns
#endif
既然类是在命名空间中定义的,那么这两种形式不应该是等价的吗?为什么在第一种情况下认为方法被定义了两次?
【问题讨论】:
标签: c++