我是 C/C++ 的新手,正在尝试模板化 Point
的结构和 RectBound
允许 double 和浮点类型。
这是点的定义
// simple Point structure
template <typename T, typename U, typename V>
struct Point{
T x;
U y;
V z; // optional
/*
Point(){
x = T();
y = U();
z = V();
}*/
Point(T _x, U _y) {
x = _x;
y = _y;
}
Point(T _x, U _y, V _z){
x = _x;
y = _y;
z = _z;
}
inline bool equals(Point & p){
return(p.x == x && p.y == y);
}
};
这里是 RectBound 结构
// Rectangular Bounds for tree
// T,U should hold double or float only
template <typename T, typename U, typename V>
struct RectBounds {
// x, y center point
T x;
U y;
// dimension width w and height h
T w, h;
//constructors
// (_x, _y): center of rectangle bound. (_w, _h): width and height
RectBounds(T _x, U _y, T _w, T _h){
x = _x;
y = _y;
w = _w;
h = _h;
}
// returns true if point p is in Rect bounds, false otherwise
inline bool contains(Point & p) {
float _w = w/2.0f;
float _h = h/2.0f;
return p.x >= x - _w && p.x < x + _w && p.y >= y - _h && p.y < y + _h;
}
// returns true if rectangle o intersects this, false otherwise
inline bool intersects( RectBounds & o){
float _w = w/2.0f;
float _h = h/2.0f;
return !(o.y + o.h/2.0f <= y - _h || o.y - o.h/2.0f >= y + _h || o.x + o.w/2.0f <= x - _w || o.x - o.w/2.0f >= x + _w);
}
};
我收到以下预期错误:(来自 RectBounds 倾斜函数中的返回行的错误)
error: request for member ‘x’ in ‘p’, which is of non-class type ‘int’
error: request for member ‘x’ in ‘p’, which is of non-class type ‘int’
error: request for member ‘y’ in ‘p’, which is of non-class type ‘int’
error: request for member ‘y’ in ‘p’, which is of non-class type ‘int’
我尝试在 RectBounds 类中定义一个点,如下所示
Point<T,U,V> cp;
但这没有帮助。
有什么建议吗?
最佳答案
首先,您的模板似乎过于复杂了。在 Point
, 可以 x
, y
, 和 z
是不同的类型?我猜不是,所以你只需要一个模板参数:
template <typename T>
struct Point{
T x;
T y;
T z;
// ...
};
对于 RectBounds
也应该这样做.
现在,您实际收到错误的原因是函数的参数类型 contains
和 intersects
.您使用过Point
和 RectBounds
.但是,这些名称是模板,而不是类型。函数参数需要有类型。由于我们给出了 Point
现在只有一个模板参数,类型可能是 Point<float>
.如您所见,我们需要提供一个模板参数。所以以下将起作用:
inline bool contains(Point<float> & p) {
但是,您似乎不想将其固定为某种特定类型。您要么只想接受 Point
与 RectBounds
的模板参数具有相同类型的 s :
inline bool contains(Point<T> & p) {
或者您希望能够接受 Point
s 具有任意类型,在这种情况下你可以制作 contains
成员函数模板:
template <typename U>
inline bool contains(Point<U> & p) {
关于c++ - 如何在另一个模板化结构中使用模板化结构 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293621/