C++向量和OpenGL

-4 c++ opengl visual-studio-2010

我写的OpenGL代码有一个奇怪的错误.作为测试,我正在创建一个球体矢量并使用push_back(s1).我在向量中添加了多个球体.但是,当我运行程序时,它只绘制最近被推入向量的球体.

#include "Sphere.h";
#include <iostream>;
#include <vector>;
using namespae std;

vector<Sphere> spheres;
Sphere s1 = Sphere(1.0, "One");
Sphere s2 = Sphere(2.0, "Two");
Sphere s3 = Sphere(3.0, "Three");

void init(void) {
    spheres.push_back(s1);
    spheres.push_back(s2);
    spheres.push_back(s3);

    for each(Sphere s in spheres) {
        cout << s.getName() << "\n";
    }
}

// OTHER CODE OMMITED

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 0.0);
    glPushMatrix();

    for each(Sphere in s) {
        s.draw();
    }

    glPopMatrix();
}
Run Code Online (Sandbox Code Playgroud)

显然有一个主要的方法,所有GL的东西都设置好了,我知道那里没有问题.

因此球体有自己的绘制方法.现在有趣的部分是在控制台输出:

Three
Three
Three
Run Code Online (Sandbox Code Playgroud)

并继续绘制s3,三次到屏幕.

所以我的问题是:为什么它只在向量中绘制最后一项三次?我也尝试使用迭代器和普通for循环,但它们都产生相同的结果.

有人有想法吗?

EDITS

getName()函数:

string Sphere::getName() {
    return name;
}
Run Code Online (Sandbox Code Playgroud)

向量的迭代器:

vector<Sphere>::iterator it;
void display() {
    for(it = planets.begin(); it != planets.end(); ++it) {
        it->draw();
    }
}
Run Code Online (Sandbox Code Playgroud)

在Sphere中绘制代码:

GLdouble r = 0.0;
GLfloat X = 0.0f;
string name = " ";

Sphere::Sphere(GLdouble ra, GLfloat x, string n)
{
    r = ra;
    X = pos;
    name = n;
}


Sphere::~Sphere(void)
{
}

void Sphere::draw(void) 
{
    glutSolidSphere(r, 10, 8);
    glTranslatef(X, 0.0, 0.0);
}

string Sphere::getName(void)
{
    return name;
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*e S 5

问题似乎是您在Sphere.cpp中定义了3个全局变量,而不是类成员变量.因此,每次构造函数运行时,它都会覆盖以前的值,而您只能看到构造的最后一个对象.

解决方案是将它们声明为成员.

在Sphere.h中,在Sphere的类定义中,put

class Sphere { 
   // constructors, your current functions, and so on...
  private:
   GLdouble r;
   GLfloat X;
   string name;
}
Run Code Online (Sandbox Code Playgroud)

最后,像这样的问题就是为什么提供一个演示问题的小例子很重要的一个例子.第一个原因是它使我们更容易确定问题的根源.第二个是它让你用小部分检查你的代码.一旦您解决了问题,您就更有可能自己识别问题.