2013-06-28 51 views
0

我有一个关于循环依赖与C++模板的问题。 我有两个模板类,Rotation3和Vector3。 旋转保持水平和垂直旋转,而矢量具有xy和z分量。C++模板依赖关系

我想每一类有一个构造函数其他:

Vector3<T>::Vector3(const Rotation3<T>& rot) 

和...

Vector3<T>::Rotation3(const Vector3<T>& vec) 

但是,因为模板不能在.cpp文件放在,并且必须位于.h中,这意味着Vector3.h和Rotation3.h必须包含对方才能使用对方的构造函数。这可能吗?

感谢您提前给予的帮助,我对C++比较陌生,我真的很想知道有经验的人会怎样去设计这个。

+0

我想知道如何在地球之间进行转换。 –

+0

为什么你不把他们放在同一个文件 – aaronman

+0

@BartekBanachewicz我想出了数学,那不是问题。你必须使用旋转矩阵和其他东西。 http://en.wikipedia.org/wiki/Rotation_matrix –

回答

2

这是有点奇怪的,通过使用#include指令不接近文件的开始,但有效。包括卫兵比平时更重要。

// Vector3.hpp 
#ifndef VECTOR3_HPP_ 
#define VECTOR3_HPP_ 

template<typename T> class Rotation3; 

template<typename T> class Vector3 
{ 
public: 
    explicit Vector3(const Rotation3<T>&); 
}; 

#include "Rotation3.hpp" 

template<typename T> 
Vector3<T>::Vector3(const Rotation3<T>& r) 
{ /*...*/ } 

#endif 

// Rotation3.hpp 
#ifndef ROTATION3_HPP_ 
#define ROTATION3_HPP_ 

template<typename T> class Vector3; 

template<typename T> class Rotation3 
{ 
public: 
    explicit Rotation3(const Vector3<T>&); 
}; 

#include "Vector.hpp" 

template<typename T> 
Rotation3<T>::Rotation3(const Vector3<T>& v) 
{ /*...*/ } 

#endif 
+0

谢谢,我明白这是如何工作的。这有点奇怪,但它是我能看到的唯一途径。谢谢,接受。 –

0

像往常一样,你可以只声明的东西,而且该声明可能足以达到目的。模板的声明与其他所有模板类似,只是省略了定义部分。

也可以在类之外定义模板类的成员函数。您可以将头部分割为只定义类和另一个实现函数。然后你可以将它们包括在内。

1

如果Vector3和Rotatio3都是模板,则不会发生任何事情,因为模板直到专门化或使用(例如vector3)才会生成对象。

您可以通过构图或继承创建另一个包含vector3和Rotation3的类,并根据需要使用它们。这也可以是一个模板(模板Vector3,模板Rotation3>示例)