在类或结构中使用运算符?

时间:2012-04-02 19:34:22

标签: c++ class struct operators

好的,所以我正在研究一些游戏逻辑,我做了一些研究(就像互联网允许的那样),但仍然没有对类和结构有一个扎实的理解,所以请温柔!

基本上,我希望能够在一行上创建一个具有属性的对象,即。

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;
};

1 个答案:

答案 0 :(得分:0)

我不知道你正在使用哪种语言,但它看起来有点像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;

您不能像在问题中提出的那样在类的定义中使用运算符。对变量的操作必须在构造函数(或其他方法)中进行。