2013-03-13 201 views
1
#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; 

} 

上面的示例按我希望的方式工作.i.e。将指针p_bar链接到bar。但是,我担心的是我指向的构造函数尚未被调用。成员指向成员对象和声明顺序的指针

此代码是否有效,或标准有什么可说的。如果不是什么替代方案。

:在我的应用程序bar是一个对象Bar(不int),但这有什么意义呢?

+0

构造函数将被调用。初始化程序列表中的顺序与构建顺序不同。成员变量按类中的声明顺序进行初始化。 – 2013-03-13 12:09:53

+0

如果'FooParent'的c-tor只存储'Bar'的地址,并且在'FooParent(&bar)'和'bar(new_x)'之间没有其他初始化,那么看起来这里没有问题 – borisbn 2013-03-13 12:09:57

+4

换句话说,它只能使用**指针**(或参考)。不与对象的副本 – borisbn 2013-03-13 12:14:05

回答

0

看看这个:

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 - 没关系),那么就不会有问题。

在另一方面,如果你给一个复制barFooParent - 这样

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将具有复制c-tor或/和赋值运算符

+0

我在谈论复制c-tor和复制分配为'FooChild',以便当它复制'FooChild'将'p_bar'分配给新复制的'Bar'。这足够好吗? – aiao 2013-03-14 10:43:40

+0

Oah ...对不起。我深深地想到了“酒吧”的复制策略......如果“它将p_bar”分配给新复制的“Bar”,我看不到任何问题“ – borisbn 2013-03-14 11:15:20