且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ Inner类不能访问外类的成员

更新时间:2023-02-15 18:43:19

(我设法弄清楚,即使你没有发布实际的错误,请在未来做),是你实际上没有实例 > Container 类中 Vect 类的函数。你应该考虑这里的设计,但是为了快速解决它(和dirty)你可以添加一个函数,在子类中设置一个 Container 实例: / p>

The reason you get an error (I managed to figure it out even though you didn't post the actual error, please do that in the future), is that you actually don't have an instance of the Container class inside the functions of the Vect class. You should probably think about the design here, but to solve it quickly (and "dirty") you could add a function which sets a Container instance in the sub-class:

class Container
{
    ...

    class Vect
    {
        Container *container;

    public:
        void SetContainer(Container &container)
            { this->container = &container; }

        float Render(void)
            {
                float T = container->time - iT;
                ...
            }

        ...
    } X;
};

int main()
{
    Container Shell;
    Shell.X.SetContainer(Shell);
    Shell.X.SetPoly(0,5);
    ...
}

一个更好的方法是使用构造函数来设置对父对象的引用(感谢juanchopanza的想法):

A better way is to set a reference to the parent object (thanks to juanchopanza for the idea) using the constructors:

class Container
{
    ...

    Container()
        : X(*this)
        { ... }

    class Vect
    {
        Container& container;

    public:
        Vect(Container& cont)
            : container(cont)
            { }

        float Render(void)
            {
                float T = container.time - iT;
                ...
            }

        ...
    } X;
};

我仍然认为这是一种肮脏的解决方案(但不像我的第一个脏)你应该考虑改变设计。

I still think it's kind of a dirty solution (but not as dirty as my first), and that you should think about changing the design instead.