好的,所以我正在研究一些游戏逻辑,我已经做了相当多的研究(尽可能多的互联网允许)并且仍然没有对类和结构有深入的了解所以请温和一点!
基本上,我希望能够创建一个具有所有属性的对象,即。
object a{1, 1, 50, 15, 5}; // create object a
我还想补充一些额外的东西,比如:
class object
{
public:
int x;
int y;
int h;
int w;
int s;
int x1;
int y1;
int ps;
int ns;
int x1 = x + w;
int y1 = y + h;
int ps = 0 + s;
int ns = 0 - s;
};
最佳答案
我不知道你使用的是哪种语言,但它看起来有点像 C++,所以这里有一个例子:
class Rect
{
public:
int x, y;
int w, h;
int right, bottom;
// This method is called a constructor.
// It allows you to perform tasks on
// the instantiation of an object.
Rect(int x_, int y_, int w_, int h_)
{
// store geometry
this->x = x_;
this->y = y_;
this->w = w_;
this->h = h_;
// calculate sides
this->right = x_ + w_;
this->bottom = y_ + h_;
}
};
// You use the constructor in your main() function like so:
Rect myObject(1, 1, 50, 15);
// And you can access the members like so:
myObject.x = 10;
myObject.right = myObject.x + myObject.w;
您不能像您在问题中提出的那样在类的定义中使用运算符。对变量的操作必须在构造函数(或其他方法)内进行。
关于c++ - 在类或结构中使用运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9982658/