我有一个头文件......
#include <SFML\Graphics.hpp>
#include <SFML\Graphics\Drawable.hpp>
#include <SFML\System.hpp>
#include <iostream>
#ifndef _SPRITE_H_
#define _SPRITE_H_
namespace Engine
{
template <class T>
class Sprite
{
sf::Vector2<T> * vector;
sf::Sprite * sprite;
public:
Sprite(sf::Vector2<T> vect, sf::Sprite spr)
{
this->sprite = spr;
this->vector = vect;
}
~Sprite();
bool Draw(T x, T y, T rotate = 0);
sf::Image GetImage()
{
return this->sprite->GetImage();
}
};
};
#endif _SPRITE_H_
源文件......
#include <SFML/Graphics.hpp>
#include <SFML/Config.hpp>
#include "sprite.h"
template <typename T>
Sprite(sf::Vector2<T> vector, sf::Sprite sprite)
{
this->sprite = sprite;
this->vector = vector;
}
template <typename T>
bool Draw(T x, T y, T rotate)
{
return false;
}
在VS 2010中,当我编译VC ++时,我收到以下错误:
Error 2 error C2143: syntax error : missing ';' before '<' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2
Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2
Error 4 error C2988: unrecognizable template declaration/definition c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2
Error 5 error C2059: syntax error : '<' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2
Error 6 error C2059: syntax error : ')' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2
Error 7 error C2143: syntax error : missing ';' before '{' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 15 1 Engine2
Error 8 error C2447: '{' : missing function header (old-style formal list?) c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 15 1 Engine2
我是C ++的总菜单(来自C#),并且一直在编译这个简单文件的问题,作为在我继续之前至少学习语法的一种方法。正如您所看到的,我所要做的就是将头文件中的模板引用到源文件,以便模板引用影响我的所有方法。
我做错了什么?我试图理解这些编译器消息,但是我在解密它们时遇到了麻烦。
更新
接下来的建议:几乎所有事情都要照顾,除此之外:
Error 1 error C2995: 'Engine::Sprite<T>::Sprite(sf::Vector2<T>,sf::Sprite)' : function template has already been defined c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 12 1 Engine2
答案 0 :(得分:2)
由于Sprite
位于Engine
内,因此应为
template <typename T>
Engine::Sprite<T>::Sprite(sf::Vector2<T> vector, sf::Sprite sprite)
{ ... }
和
template <typename T>
bool Engine::Sprite<T>::Draw(T x, T y, T rotate)
{
return false;
}
或者,正如@jli建议的那样,也将它放在命名空间Engine
中:
namespace Engine {
template <typename T>
Sprite<T>::Sprite(sf::Vector2<T> vector, sf::Sprite sprite)
{ ... }
template <typename T>
bool Sprite<T>::Draw(T x, T y, T rotate)
{
return false;
}
}