如何解决cpp 文件中的类函数产生未解析的外部符号,即使它在头文件 vc++ 中正确声明
这是我的第一个堆栈溢出问题,所以请告诉我如何使问题更清楚!
我已经编码 c++ 一年多了,每次我创建一个类时,我只是纯粹地坚持 .hpp 文件,因为我永远无法通过 cpp 和 hpp 文件获得类,所以我创建了一个帐户来询问这个问题,我下面的代码显示了这应该如何工作,但由于某种原因,我收到了一个未解决的外部符号错误:Severity Code Description Project File Line Suppression State Error LNK2001 unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,struct Vec2<int> const &)" (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV01@AEBU?$Vec2@H@@@Z) Coconut 2d Engine C:\dev\Coconut Engine\Coconut 2d Engine\Coconut.obj
此代码不起作用(不是错误中的代码但存在相同问题):
类.hpp
#ifndef CLASS_HPP
#define CLASS_HPP
class TestClass {
public:
int a;
TestClass() { a = 0; }
void IncA(); //increment a
}
#endif
class.cpp
#include "class.hpp"
void TestClass::IncA() {
this->a++;
}
这不会产生语法错误,但我仍然得到未解析的外部符号
谢谢你的帮助!
编辑:
这是实际的代码(处于完全混乱的状态):
Vector2.hpp
#ifndef VECTOR2_HPP
#define VECTOR2_HPP
#include <iostream>
template <typename T> struct Vec2 {
public: //public variables + constuctors
T x;
T y;
Vec2() { this->x = (T)0; this->y = (T)0; }
void TestFunction();
Vec2(T x = (T)0,T y = (T)0) {
this->x = x;
this->y = y;
}
public: //public funcs
//inline Vec2<T> operator+(const Vec2<T>& r) const; //r = right
//inline Vec2<T>& operator-(const Vec2<T>& l,const Vec2<T>& r) const; //r = right
//inline Vec2<T>& operator*(const Vec2<T>& l,const Vec2<T>& r) const; //r = right
//inline Vec2<T>& operator/(const Vec2<T>& l,const Vec2<T>& r) const; //r = right
friend std::ostream& operator<<(std::ostream& os,const Vec2<T>& out);
};
typedef Vec2<int> Vec2i;
typedef Vec2<float> Vec2f;
typedef Vec2<double> Vec2d;
template<typename T>
using Vector2 = Vec2<T>;
typedef Vector2<int> Vector2i;
typedef Vector2<float> Vector2f;
typedef Vector2<double> Vector2d;
#endif
Vector2.cpp
#include "vector2.hpp"
template<typename T>
void Vec2<T>::TestFunction() {
this->x++;
this->y++;
}
template<typename T>
std::ostream& operator<<(std::ostream& os,Vec2<T>& out) {
os << "(" << out.x << "," << out.y << ")";
return os;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。