簡體   English   中英

類中的結構?

[英]structs within classes?

我上課了。 我已經制作了兩個單獨的文件,分別是標頭和c ++文件。 我正在使用它為我正在開發的opengl游戲創建一個或多或少的Light'object'。 這是文件:Light.h

#ifndef LIGHT_H
#define LIGHT_H


class Light
{
    public:
        Light(float ix, float iy, float iz, float ir, float ig, float ib , float ia, int itype, int iindex);
        virtual ~Light();
        float x,y,z;
        int index;
        int type;
        struct ambient
        {
            float r, g, b, a;
        };
        struct diffuse
        {
            float r, g, b, a;
        };
        struct specular
        {
           float r, g, b, a;
        };
    protected:
    private:
};

#endif // LIGHT_H

並且,Light.cpp

#include "../include/Light.h"

Light::Light(float ix, float iy, float iz, float ir, float ig, float ib , float ia, int itype, int iindex)
{
    index=iindex;
    type=itype;
    x=ix;
    y=iy;
    z=iz;
    ambient.r = 0.2;
    ambient.g = 0.2;
    ambient.b = 0.2;
    ambient.a = 1.0;
    specular.r = 0.8;
    specular.g = 0.8;
    specular.b = 0.8;
    specular.a = 1.0;
    diffuse.r = ir;
    diffuse.g = ig;
    diffuse.b = ib;
    diffuse.a = ia;
}

Light::~Light()
{
    //dtor
}

當我嘗試編譯時,它拋出一條錯誤消息:error:'。'之前的預期unqualified-id。 令牌| 對於我為結構的一個成員(環境,漫反射,鏡面反射)分配值的每一行,首先,我什至無法解釋該錯誤。 不知道這意味着什么。 其次,我看不到自己在做錯什么。 請幫忙!

內容如下:

#ifndef LIGHT_H
#define LIGHT_H


class Light
{
    public:
        Light(float ix, float iy, float iz, float ir, float ig, float ib , float ia, int itype, int iindex);
        virtual ~Light();
        float x,y,z;
        int index;
        int type;
        struct
        {
            float r, g, b, a;
        } ambient;
        struct
        {
            float r, g, b, a;
        } diffuse;
        struct
        {
           float r, g, b, a;
        } specular;
    protected:
    private:
};

#endif // LIGHT_H

基本的問題是,您在聲明這些結構已經存在並給出了類型的名稱,但是您沒有在聲明該類型的任何變量。 因為從您的用法來看,很明顯這些結構的類型不需要名稱(它們可以是匿名結構),所以我在聲明后移動了名稱,因此您在聲明變量。

正如GMan指出的那樣,這仍然不是最佳選擇。 這是解決此問題的更好方法:

#ifndef LIGHT_H
#define LIGHT_H


class Light
{
    public:
        Light(float ix, float iy, float iz, float ir, float ig, float ib , float ia, int itype, int iindex);
        virtual ~Light();
        float x,y,z;
        int index;
        int type;

        struct Color {
            float r, g, b, a;
        };

        Color ambient, diffuse, specular;
    protected:
    private:
};

#endif // LIGHT_H

暫無
暫無

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

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