c++ - 我不明白这个链接错误

标签 c++ c++11

我不明白这个链接错误。 我有 2 个类(class):

#include "Vector3.h"
#include "Quaternion.h"

template<typename T>
class Point3 final
{
public:
   constexpr Point3(const Vector3<T>& vec)
   : x(vec.x), y(vec.y), z(vec.z)
   {}

   constexpr operator const Vector3<T>() const
   {
      // It is the equivalent of Vector3 = Point3 - Origin
      return Vector3<T>(x, y, z);
   }

  constexpr operator Vector3<T>() const
  {
     // It is the equivalent of Vector3 = Point3 - Origin
     return Vector3<T>(x, y, z);
  }

  T x = T(0);
  T y = T(0);
  T z = T(0);

  friend Vector3<T>;
  friend Quaternion<T>;

  friend Vector3<T> operator*( const Quaternion<T>& lhs, const Vector3<T>& rhs);
  friend Vector3<T> operator*( Vector3<T> lhs, const Vector3<T>& rhs);
};

typedef Point3<Float32> Point3f;

template<typename T>
class Vector3 final
{
public:

  constexpr Vector3()
  {}

  constexpr Vector3(T _x, T _y, T _z)
  : x(_x), y(_y), z(_z)
  {}

  T x = T(0);
  T y = T(0);
  T z = T(0);

};

typedef Vector3<Float32> Vector3f;

我也有一个四元数类,我相信细节无关紧要,但是这个类有一个非成员运算符*:

 template<typename T>
 Vector3<T> operator*( const Quaternion<T>& lhs, const Vector3<T>& rhs)
 {
    // nVidia SDK implementation
    Vector3<T> qvec(lhs.x, lhs.y, lhs.z);
    Vector3<T> uv = cross(qvec, rhs) * T(2.0) * lhs.w;    //uv = qvec ^ v;
    Vector3<T> uuv = cross(qvec, uv) * T(2.0);    //uuv = qvec ^ uv;
    return rhs + uv + uuv;
 }

现在这些行产生链接错误,但为什么呢?

Math::Point3<Float32> pt = -Math::Point3<Float32>::UNIT_Z;
Math::Vector3<Float32> vec = orientation_*pt; // link error here (orientation is a Quaternion<Float32>)
//Math::Vector3<Float32> vec = orientation_*Math::Vector3<Float32>(pt); // this solve the link error.

这里是链接错误

Undefined symbols for architecture x86_64:
  Math::operator*(Math::Quaternion<float> const&, Math::Vector3<float> const&), referenced from:
  GfxObject::Procedural::BoxGenerator::addToTriangleBuffer(GfxObject::Procedural::TriangleBuffer&) const in ProceduralBoxGenerator.o

更新

我发现有 2 个问题与此非常接近,但问题在于差异。

在: question 1question 2

但在我的例子中,我需要在 2 个模板类之间进行转换,而不是在同一个类和 2 个实例之间进行转换。我希望这会有所帮助!

最佳答案

尝试确保编译器知道您的友元声明应该是模板特化,而不是全新的非模板函数的声明:

friend Vector3<T> operator* <> (const Quaternion<T>& lhs, const Vector3<T>& rhs);

C++ 常见问题解答中讨论了这个常见错误 here .

关于c++ - 我不明白这个链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17078262/

相关文章:

c++ - 为什么我的快速排序仅在数组中的 1 个位置出错?

c++ - 如何比较c++列表中的两个连续元素

c++ - 在 C++ 中正确设置局部环境变量

c++ - 无法使用重载运算符<<来打印对象的值

c++ - 在没有开销的情况下实现push_back的最佳方法是什么

C++程序查找语法错误

c++ - 在不重建 C++ 的情况下更改常量变量

c++ - 为 vector 的 vector 提供平坦迭代器的优雅方式

c++ - 自定义文字适用于 long double 但不适用于 double,并且适用于按值传递但不按引用传递

c++ - 从 C++ 字符串中删除不允许的字符的最优雅、最有效的方法?