简体   繁体   中英

using operators inside class or struct?

OK so I am working on some game logic, I have done a fair bit of research (as much as the internet will allow) and still don't have a solid understanding of class and struct so please go gentle!

Basically, I want to be able to create an object with the properties all on one line ie.

object a{1, 1, 50, 15, 5}; // create object a 

and I want some extra stuff to be made up aswell like:

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

I don't know which language you're working with, but it looks a bit like C++, so here's an example:

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;

You cannot use operators inside the definition of a class as you proposed in your question. Operations on variables must take place inside a constructor (or other method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM