簡體   English   中英

一個關於opengl,c ++和對象的非常簡單的問題

[英]a very simple question about opengl, c++ and objects

我在C ++中有一個非常簡單的openGL程序。 我制作了一個Sphere對象,該對象只是繪制一個球體。 我想有一個全局變量,它在main()中實例化,即sphere = Sphere(radius,etc),然后在draw()中繪制,即sphere.draw(),但是C ++不允許我這樣做。 另外,如果我在main()中具有對球體的引用,則無法將其傳遞給draw函數,因為我自己還沒有定義draw函數。 這個偽代碼可能會更好地解釋它:

include "sphere.h"
Sphere sphere;   <- can't do this for some reason

draw()
{
    ...
    sphere.draw()
}

main()
{
    glutDisplayFunc(draw)
    sphere = Sphere(radius, etc)
}    

我敢肯定這很簡單,但是對於Google來說,找到答案並相信我已經嘗試過是一件困難的事情。 我知道使用全局變量是“不好的”,但似乎沒有其他選擇。 我最終希望擁有另一個名為“世界”的類,其中包含對球體的引用和繪制函數,但是另一個問題是我不知道如何將glutDisplayFunc重定向到類函數。 我嘗試了glutDisplayFunc(sphere.draw),顯然這是錯誤的。

編譯器錯誤是:../src/Cplanets.cpp:9:錯誤:沒有匹配函數可以調用'Sphere :: Sphere()'../src/Sphere.cpp:28:注意:候選對象是:Sphere: :Sphere(std :: string,float,float,float)../src/Sphere.cpp:13:注意:Sphere :: Sphere(const Sphere&)

球類是:

/*
 * Sphere.cpp
 *
 *  Created on: 3 Mar 2011
 *      Author: will
 */

#include <GL/glut.h>
#include <string>

using namespace std;

class Sphere {

public:

    string name;
    float radius;
    float orbit_distance;
    float orbit_time;

    static const int SLICES = 30;
    static const int STACKS = 30;

    GLUquadricObj *sphere;


    Sphere(string n, float r, float od, float ot)

    {

        name = n;
        radius = r;
        orbit_distance = od;
        orbit_time = ot;
        sphere = gluNewQuadric();

}

void draw()
{
    //gluSphere(self.sphere, self.radius, Sphere.SLICES, Sphere.STACKS)
    gluSphere(sphere, radius, SLICES, STACKS);
}

};

您正在處理兩個構造函數調用:

Sphere sphere;

這嘗試調用未聲明的默認構造函數Sphere::Sphere()

sphere = Sphere(radius, etc);

這將調用構造函數並接受兩個參數,我認為這是唯一提供的參數。

像這樣做:

include "sphere.h"
Sphere *sphere;

draw()
{
    ...
    sphere->draw();
}

main()
{
    sphere = new Sphere(radius, etc);
    glutDisplayFunc(draw);
}    

Sphere類已覆蓋默認構造函數。 如果在類定義中未指定構造函數,則編譯器會自動提供默認構造函數(即Sphere::Sphere() )。 由於Sphere類已使用帶有四個參數的構造函數覆蓋了它,因此,類本身的工作就是指定默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM