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

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

最佳答案

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

相关文章:

c++ - 创建用于创建和打印 vector 的 C++ 类对象

c - _Alignas 结构成员使用 clang & C11

c++ - C++ 循环中的指数运算符

c++ - SFML C++ 绘制形状 vector

java - 尝试使用 String 变量和 Class.forName 启动 Activity ,不断抛出 ClassNotFound 帮助

C++ 内存分配和重写 vector 类

c - 链表和输入

c - 从指向结构中不同变量的指针访问结构的第一个变量

java - Android 无法找到我的 JNI native 库函数

c++ - Visual Studio 的 "preprocess current file"插件? (C++)