C ++属性私有访问

时间:2014-01-25 23:13:19

标签: c++ attributes private

我有一个类Sphere(.ccp和.h),它有一些声明为私有的attributs。我读到这些属性可以被类本身使用,但是当我尝试在Sphere.cpp中使用一个attribut时,它会说“使用非声明的标识符”。

Sphere.h:

class Sphere {
public:
    inline Sphere () {}
    inline Sphere (const Vec3Df spherePos, const float radius, const Material2 & mat) :       spherePos(spherePos), radius(radius), mat (mat) {
    updateBoundingBox();
    }
    virtual ~Sphere ()
    {}

    inline const Vec3Df  getSpherePos () const { return spherePos; }
    inline Vec3Df getSpherePos () { return spherePos; }

    inline const float getRadius () { return radius; }

    inline const Material2 & getMaterial () const { return mat; }
    inline Material2 & getMaterial () { return mat; }

    inline const BoundingBox & getBoundingBox () const { return bbox; }
    void updateBoundingBox ();

    bool intersect(Ray ray);

private:
    Vec3Df spherePos;
    float radius;
    Material2 mat;
    BoundingBox bbox;

};

我称之为attributs:

Vec3Df pointGauche = spherePos;

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

私人班级成员只能从班级成员访问:

struct Foo
{
    static void bar(Foo &);
    int zoo() const;

private:
    int x;
    typedef void * type;
    type gobble(type);
};

void * Foo::gobble(void * q)
{
   x = 10;          // OK
   type p = q;      // OK
}

void Foo::bar(Foo & rhs)
{
    rhs.x += 10;    // OK
    type p = &rhs;  // OK
    rhs.zip();      // OK 
}

int main()
{
    Foo f;
    // f.x += 20;       // Error, Foo::x inaccessible
    // Foo::type p;     // Error, Foo::type inaccesible
    // f.gobble(NULL);  // Error, Foo::gobble inaccessible
    Foo::bar(x);        // OK, Foo::bar is public
    return x.zoo();     // OK, Foo::zoo is public
}

答案 1 :(得分:1)

您需要指定属于void updateBoundingBox()的类:

// note the Sphere:: part
void Sphere::updateBoundingBox() {

    // now you have access to private instance variables:
    Vec3Df pointGauche = spherePos; 
    Vec3Df pointDroit; 
    Vec3Df pointHaut; 
    Vec3Df pointBas; 
    bbox = BoundingBox(spherePos); 

}

答案 2 :(得分:1)

你的定义是错误的:

void updateBoundingBox(){ Vec3Df pointGauche = spherePos; Vec3Df pointDroit; Vec3Df pointHaut; Vec3Df pointBas; bbox = BoundingBox(spherePos); }

尝试这种方式:

void Sphere::updateBoundingBox()
{
Vec3Df pointGauche = spherePos;
Vec3Df pointDroit;
Vec3Df pointHaut;
Vec3Df pointBas;
bbox = BoundingBox(spherePos);
}