我有许多类都使用相同的宽度和高度变量,并且还使用函数来检查点是否在边界内。类似的东西:
class map
{
int height;
int width;
bool pointExists(int x, int y)
{
if(x < 0 || y < 0 || x >width-1 || y>height-1)
return false;
return true;
}
};
class somethingElse
{
int height;
int width;
bool pointExists(int x, int y)
{
if(x < 0 || y < 0 || x >width-1 || y>height-1)
return false;
return true;
}
};
所以...我希望每个班级都可以使用宽度和高度,并且每个班级都可以使用“pointExists”功能。我知道我可以用全局变量做到这一点,但我想知道是否有人能告诉我一个更好的方法......
答案 0 :(得分:3)
使它成为基类和它的子类
class Element {
protected:
int height;
int width;
public:
bool pointExists(int x, int y)
{
return x >= 0 && y >= 0 && x < width && y < height);
}
};
class map : public class Element {
};
class somethingElse : public class Element {
};
答案 1 :(得分:1)
您可以使用组合,而不是继承,例如:
class Dimension
{
unsigned int height;
unsigned int width;
bool pointExists(unsigned int x, unsigned int y) const
{
return x < width && y < height;
}
};
class map { Dimension dim; };
class somethingElse { Dimension dim; };
答案 2 :(得分:0)
class somethingElse : public class map {
// much more things
};
阅读更多关于C ++的资料,特别是关于它的rule of three(现在C ++ 11中的五条规则)
答案 3 :(得分:0)
声明另一个类点&amp;将变量/函数移动到它。然后继承所有需要它的类中的点。
class Area
{
int height;
int width;
bool pointExists(int x, int y)
{
if(x < 0 || y < 0 || x >width-1 || y>height-1)
return false;
return true;
}
};
class map: private Area{
};
class somethingElse: private Area{
};
答案 4 :(得分:0)
除了继承示例之外,您还可以将width, height and pointExists
定义为静态,因此您不需要对象实例来使用它。我在自己的代码中使用这种方法来创建类似clipping helper
类的东西。所有访问都是通过静态方法完成的,所以我不需要创建实例,它只需将代码和所需的变量包装到一个类中。
您也可以使用static pointExists(x,y)
代码和静态变量创建一个基类,并继承它,因此每个类可以有不同的height/width
值。
编辑: 所以这是一个如何看起来的例子:
class MyClipper {
static int width;
static int height;
public static bool pointExists( int x, int y );
public static void setWidth( int width );
public static void setHeight( int height );
};
// somewhere in your scene initialization
MyClipper::setWidth( 100 );
// another place in your code
bool b = MyClipper::pointExists( 1, 1 );
答案 5 :(得分:0)
这是继承扮演重要角色的确切问题。
在继承中,你有一个父类(就像我们的父母一样)和一个子类(比如我和我的兄弟姐妹),所以子类可以访问父类中的变量和函数以及变量并且功能不是私密的(就像有一些秘密,父母不想透露给他们的孩子,所以在编程中秘密是private
,而有一些秘密,我们的父母告诉我们但不想要我们向其他人透露,在编程中秘密是protected
,但如果他们是public
你可以告诉任何人。)
1-创建一个Parent类(在你的case类map {...};中)并编写你的变量(height,width)和函数(void pointExists(int,int);)。
2-创建Child类(类SomeOtherClass:public map {...};)并且如您所希望的那样编写全局函数,您将不需要编写已在Parent类中编写的相同变量和函数。
3-创建Child类的对象,并通过该对象设置高度和宽度的值,最后调用您的函数(作为childObject.pointExists(x,y))。
答案 6 :(得分:-1)
第二种方式是:
<强> utils.h 强>
bool in_bounds(int x, int y, int w, int h);
<强> utils.cpp 强>
#include "utils.h"
bool in_bounds(int x, int y, int w, int h)
{
if (x < 0 || y < 0 || x > w - 1 || y > h - 1)
{
return false;
}
return true;
}
如果不想要使用继承,或者无法使用继承,我的方法很好。