成员指针指向成员对象和声明顺序 [英] Member pointer to member object and declaration order

查看:343
本文介绍了成员指针指向成员对象和声明顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

class FooParent
{
    public:
        FooParent(int* new_p_bar)
        {
            p_bar = new_p_bar;
        }
    public:
        int* p_bar;
};

class FooChild : public FooParent
{
    public:
        int bar;
    public:
        FooChild(int new_x)
        :FooParent(&bar)
        ,bar(new_x) \\ point of concern
            {} 
};

int main()
{ 
    FooChild foo(8);
    std::cout << foo.bar << std::endl;

}

上面的例子工作原理就像我想要的。将指针 p_bar 链接到 bar 。但是,我的问题是我指向的构造函数尚未被调用的成员。

The above example works as I want it to .i.e. link the pointer p_bar to bar. However, my concern is that I am pointing to a member whose constructor is not yet called.

这个代码是否有效,或者标准有什么要说的。

Is this code valid, or does the standard have something to say about it. If not what is the alternative.

注意:在我的应用程序 bar 对象 Bar (不是 int ),这有什么含义吗?

NOTE: In my application bar is an Object Bar (not int), does this have any implications?

推荐答案

看看这个:

class FooParent {
    public:
        FooParent(int* new_p_bar)
        {
            p_bar = new_p_bar;
            *p_bar = 99; // this has no sense
        }
        void set99() {
            *p_bar = 99; // this - has
        }
    public:
        int* p_bar;
};

class FooChild : public FooParent
{
    public:
        int bar;
    public:
        FooChild(int new_x)
        :FooParent(&bar)
        ,bar(new_x) // point of concern
            {} 
};

int main()
{ 
    FooChild foo( 42 );
    std::cout << foo.bar << std::endl;
    foo.set99();
    std::cout << foo.bar << std::endl;
}

LWS

我的意思是如果 FooParent 构造函数只向外部存储指针 int (或 Bar - 无关紧要)

I mean that if FooParent's constructor only stores a pointer to external int (or Bar - doesn't matter) then there will be no problem.

另一方面,如果您给予 bar code>到 FooParent - 像这样

In other hand, if you'll give a copy of bar to FooParent - like this

class FooParent
{
    public:
        FooParent(Bar new_p_bar)
        {
            p_bar = new_p_bar;
        }
        void set99() {
            p_bar = 99; // this - has
        }
    public:
        Bar p_bar;
};

class FooChild : public FooParent
{
    public:
        Bar bar;
    public:
        FooChild(Bar new_x)
        :FooParent(bar)
        ,bar(new_x) // point of concern
            {} 
};

int main()
{ 
    FooChild foo( 42 );
    std::cout << foo.bar << std::endl;
    foo.set99();
    std::cout << foo.bar << std::endl;
}

LWS

这不会工作。即使 Bar 将有一个副本操作符或/和赋值运算符

this will not work. Even if Bar will have a copy c-tor or/and assignment operator

这篇关于成员指针指向成员对象和声明顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆