课程中的结构?

Kee*_*elx 2 c++ struct class codeblocks

我上课了.我制作了两个单独的文件,标题和c ++文件.我正在使用它为我正在进行的opengl游戏创建一个或多或少的Light'对象'.这是文件: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
Run Code Online (Sandbox Code Playgroud)

而且,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
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,它会抛出一个错误说:错误:在'.'之前预期的unqualified-id.令牌| 对于我为结构的一个成员赋值的每一行(环境,漫反射,镜面反射)首先,我甚至无法解释这个错误.不知道这意味着什么.其次,我没有看到我做错了什么.请帮忙!

Omn*_*ous 7

这应该是这样的:

#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
Run Code Online (Sandbox Code Playgroud)

基本问题是您声明结构存在并给出类型的名称,但您没有声明该类型的任何变量.因为,根据您的使用情况,很明显这些结构的类型不需要名称(它们可能是匿名结构)我在声明后移动了名称,因此您声明了一个变量.

正如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
Run Code Online (Sandbox Code Playgroud)

  • @Keelx:最好是拥有一个`Color`类,并让成员`颜色环境; 颜色漫射; 颜色镜面;`.你在重复所有类型:[**永远不要重复自己**](http://en.wikipedia.org/wiki/Don't_repeat_yourself). (3认同)