我有一个包含类的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
Run Code Online (Sandbox Code Playgroud)
如果在同一个项目中我从多个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
Run Code Online (Sandbox Code Playgroud)
由于类是在命名空间内定义的,这两种形式不应该是等价的吗?为什么在第一种情况下认为方法定义了两次?
如果这个问题没有意义或者看起来很简单,但我想了解这些头文件是如何工作的,请原谅我
是否可以在头文件内部声明 int 等类型的变量?
我有以下代码,我声明窗口和窗口尺寸的行有问题。编译器说它们有多个定义,首先在主文件中定义,我只是在主文件中定义了#include“core.h”。 h”并在 core.cpp 中再次定义,其中我再次有一个#include“core.h”。
#ifndef SFMLAPP_CORE_H
#define SFMLAPP_CORE_H
#include "SFML/Graphics.hpp"
#include <iostream>
sf::RenderWindow* window;///Window
float ScreenW,ScreenH;///Dimensions of the window
struct position ///used in position handiling
{
float x=-1;
float y=-1;
};
void printText(position pos,std::string Text,float size,float outlineSize);
#endif //SFMLAPP_CORE_H
Run Code Online (Sandbox Code Playgroud) c++ ×2