我试图在c++中使用结构,但它不起作用

I am trying to use structure in c++ but its not working

本文关键字:结构 不起作用 c++      更新时间:2023-10-16

在此方法

void Sierpinski(GLintPoint points) {
    glClear(GL_COLOR_BUFFER_BIT);
    GLintPoint T[3] = {{10,10},{600,10},{300,600}};
    int index=rand()%3;
    GLintPoint point=points[index];
    drawDot(point.x, point.y);
    for (int i = 0;i<55000;i++) {
        index=rand()%3;
        point.x=(point.x+points[index].x)/2;
        point.y=(point.y+points[index].y)/2;
        drawDot(point.x,point.y);
    }
    glFlush();
}

使用了我创建的结构

struct GLintPoint {
GLint x,y;
};

它说有一个错误,"没有操作符"[]"匹配这些操作数,操作符类型是GLintPoint[int]",我试图从点到点赋值。我确实用了右括号,这里是个整型,那么问题是什么呢?仅供参考,这段代码是用用户通过用鼠标点击屏幕绘制最初的3点来绘制Sierpinski垫圈。如果你想看的话这是整个程序。

#include <windows.h>
#include <gl/Gl.h>
#include "glut.h"
#include <iostream>
using namespace std;
const int screenWidth = 640;
const int screenHeight = 480;
struct GLintPoint {
    GLint x,y;
};
void display (void){
    glClear(GL_COLOR_BUFFER_BIT);
    //glColor3f(1.0,1.0,1.0);
    glFlush();
}
void drawDot( GLint x, GLint y)
{
glBegin( GL_POINTS );
glVertex2i( x, y );
glEnd();
}
void Sierpinski(GLintPoint points) {
    glClear(GL_COLOR_BUFFER_BIT);
    GLintPoint T[3] = {{10,10},{600,10},{300,600}};
    int index=rand()%3;
    GLintPoint point=points[index];
    drawDot(point.x, point.y);
    for (int i = 0;i<55000;i++) {
        index=rand()%3;
        point.x=(point.x+points[index].x)/2;
        point.y=(point.y+points[index].y)/2;
        drawDot(point.x,point.y);
    }
    glFlush();
}
void myMouse(int button, int state, int x, int y){
    static GLintPoint corner[2];
    static int numCorners = 0;
    if(state == GLUT_DOWN){
        if(button == GLUT_LEFT_BUTTON){
            corner[numCorners].x = x;
            corner[numCorners].y = screenHeight - y;
            if(++numCorners ==2 ){
                glRecti(corner[0].x, corner[0].y, corner[1].x,    corner[1].y);
               numCorners = 0;
            glFlush();
        }
    }
        else if(button == GLUT_RIGHT_BUTTON){
            glClear(GL_COLOR_BUFFER_BIT);
            glFlush();
        }   
}
}
void myInit() {
    glClearColor(1.0,1.0,1.0,0.0);
    glClear(GL_COLOR_BUFFER_BIT);
   glColor3f(0.0f,0.0f,0.0f);
   glPointSize(2.0);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   gluOrtho2D(0.0, (GLdouble)screenWidth, 0.0, (GLdouble)screenHeight);
}

void main (int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(screenWidth, screenHeight);
    glutInitWindowPosition(100,150);
    glutCreateWindow("mouse dots");
    glutDisplayFunc(display);
    glutPostRedisplay();
    glutMouseFunc(myMouse);
   myInit();
   glutMainLoop();
}

我从函数参数points的名称推断,您打算该函数接受点数组。但实际上它只写了一个

所以当你写points[index]编译器正在寻找operator[]在你的GLintPoint结构(没有一个)。

如果你把函数原型改成一个GLintPoint s数组,我想你会有更好的运气。