【发布时间】:2016-03-10 01:46:52
【问题描述】:
我正在尝试编写一个具有 3 个抽象类(Base_A、Base_B 和 Base_C)的 C++ 程序,并且它们每个都有一个派生类(分别为 Derived_A、Derived_B 和 @987654326 @)。
现在,我想创建Derived_C 的对象z(通过boost::shared_ptr)。要初始化z 我想使用y(通过boost::shared_ptr),它是Derived_B 的成员,并初始化y 我想使用x(通过boost::shared_ptr),它反过来又是Derived_A 的成员。
我面临的问题是我想检索成员K的值,它属于类Derived_B,但是下面这行
std::cout << z->barC->K << std::endl;
返回 0.0 而不是 50.0(应该是这样)。
我错过了什么?可能与 Derived_B 和 Derived_C 类的构造函数中的 shared_ptr 成员的初始化有关?
代码如下:
//----- 啊.h -----
class Base_A{
public:
double K;
Base_A(){};
Base_A(const double& _K);
virtual ~Base_A(){};
virtual double operator()(const double& _S) const = 0;
};
class Derived_A :public Base_A{
public:
double K;
Derived_A(const double& _K);
~Derived_A(){};
double operator()(const double& _S)const;
};
//-- A.cpp -----
Base_A::Base_A(const double& _K)
:K(_K){};
Derived_A::Derived_A(const double& _K)
:K(_K){};
double Derived_A::operator()(const double& _S) const {
return std::max(_S - K, 0.0);
}
//--------------------------------------------- ----------------------------------
//----- B.h -----
class Base_B{
public:
double S;
double K;
boost::shared_ptr<Base_A> fooB;
Base_B(){};
virtual ~Base_B(){};
// other pure virtual functions...
};
class Derived_B :public Base_B{
public:
double S;
double K;
boost::shared_ptr<Derived_A> fooD;
Derived_B(const double& _K, boost::shared_ptr<Derived_A> _fooD);
~Derived_B(){};
// declaration of the pure virtual functions...
};
//----- B.cpp -----
Derived_B::Derived_B(const double& _K, boost::shared_ptr<Derived_A> _fooD)
:K(_K){
fooD = boost::shared_ptr<Derived_A>(_fooD);
};
//--------------------------------------------- --------------------------------
//----- C.h -----
class Base_C{
public:
boost::shared_ptr<Base_B> barB;
Base_C(){};
virtual ~Base_C(){};
// other pure virtual functions...
};
class Derived_C :public Base_C{
public:
boost::shared_ptr<Base_B> barC;
Derived_C(boost::shared_ptr<Base_B> _barC);
~Derived_C(){};
// declaration of the pure virtual functions...
};
//-- C.cpp -----
Derived_C::Derived_C(boost::shared_ptr<Base_B> _barC){
barC = _barC;
};
//--------------------------------------------- ----------------------------------
//----- Main.cpp -----
void main(){
double K= 50.0;
double S= 100.0;
boost::shared_ptr<Derived_A> x(new Derived_A(K));
boost::shared_ptr<Derived_B> y(new Derived_B(K,x));
boost::shared_ptr<Derived_C> z(new Derived_C(y));
std::cout << z->barC->K << std::endl; // returns 0.0 instead of 50.0
}
提前致谢。
【问题讨论】:
标签: c++ boost polymorphism shared-ptr