【问题标题】:C++ attributes private accessC++ 属性私有访问
【发布时间】:2014-01-25 23:13:19
【问题描述】:

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

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;

};

我这样称呼属性:

Vec3Df pointGauche = spherePos;

有人可以帮我吗?

【问题讨论】:

  • 你在成员函数中吗?
  • “类”和“文件”是不同的东西。
  • @EricFortin 是的,调用在.cpp中的函数updateboundingBox中
  • @otisonoza 这是无效的 updateBoundingBox(){ }
  • @otisonoza 我意识到我没有将 Sphere 放在 updateBoundingBox 前面。它解决了问题。

标签: c++ attributes private


【解决方案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
}

【讨论】:

  • 谢谢你的解释:)
【解决方案2】:

你需要指定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); 

}

【讨论】:

    【解决方案3】:

    你的定义是错误的:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-05
      • 2014-11-21
      • 2014-01-14
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 2020-08-31
      相关资源
      最近更新 更多