开发者

How to get instance of nested class in C++

开发者 https://www.devze.com 2022-12-21 23:23 出处:网络
I have the following code: class outer { struct inner { int var1; int var2; inner() { var1 = 1; var2 = 2; } };

I have the following code:

class outer
{
    struct inner
    {
        int var1;
        int var2;
        inner() { var1 = 1; var2 = 2; }
    };

    inner inner_instance;

public:
    const inner *get_inner() { return &inner_instance; }
};

int main(int argc, char *argv[])
{
    // 1
    outer outer_instance;
    cout << outer_instance.get_inner()->var1 << endl;

    // 2
    // this cannot be compiled because outer::inner is private
    //const outer::inner *inner_ref = outer_instance.get_inner();
    //cout << inner_ref->var1;

    // 3
    const int *inner_var2 = (int *) outer_instance.get_inner();
    inner_var2++;
    cout << *inner_var2 << endl;

    return 0;
}

I unde开发者_高级运维rstand why No.2 cannot be compiled. I just do not know what is the design idea of the compiler that allows access to the public fields of a private nested class but not the nested class itself, like No.1. The instance data is still in the memory. If I know the structure of such private nested class, I can still achieve assigning like No.3 does.

Does that mean it is better not to return pointer or reference of a private nested class in a public function? And if I really have to return something about the nested class to the outer world, make it public?

Thanks!


Put the struct inner definition in the public if you want to use it outside outer class.

class outer
{
public:
    struct inner
    {
        int var1;
        int var2;
        inner() { var1 = 1; var2 = 2; }
    };
private:
    inner inner_instance;
public:
    const inner *get_inner() { return &inner_instance; }
};


You are right, it is best if the types used in the public API are not private. They may be forward declared only, though (if you only use pointers or references on the API).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号