gpt4 book ai didi

C++继承指针

转载 作者:行者123 更新时间:2023-11-30 03:06:24 25 4
gpt4 key购买 nike

我很难描述我的问题。我有两个类,我会说 Base_ADerived_A。从名称可以看出,类Derived_A 派生自Base_A。在我的程序中还有另外两个类 Base_BDerived_B (也具有继承)。类Base_A包含Base_B的对象,类Derived_A包含Derived_B的对象。

class Base_A {
public:
Base_A() {}
virtual ~Base_A() {}

Base_B b_;
Base_B* pointer_;

void init() {
b_ = Base_B();
pointer_ = &b_;
pointer_->setValue(1);
}

void print() {
pointer_->getValue();

}
};

class Derived_A: public Base_A {
public:
Derived_A() {}
virtual ~Derived_A() {}

Derived_B b_;
Derived_B* pointer_;

void init() {
b_ = Derived_B();
pointer_ = &b_;
pointer_->setValue(2);
pointer_->increaseValue();
}
};

class Base_B {
public:
Base_B() {}
virtual ~Base_B() {}

int value_;

void setValue(int value) {
value_ = value;
}

void getValue() {
cout << "Base_B: " << value_ << endl;
}
};

class Derived_B: public Base_B {
public:
Derived_B() {}
virtual ~Derived_B() {}

void increaseValue() {
value_++;
}
};

int main() {
Derived_A derived_A = Derived_A();
derived_A.init();
derived_A.print();

return 0;
}

如何查看 A 的每个类都有一个 B 类的对象和指向该对象的指针。我的问题是,当我调用函数 print() 时,它不使用 Derived_B* pointer_,而是尝试访问 Base_B* pointer_,这是不存在的。我怎么能在我的程序中说,它应该根据类采用指针?或者我是否需要在 Derived_A 类中声明 Base_B* pointer_,例如:

Base::pointer_ = pointer_;

也许有其他方法或算法可以解决我的问题?

非常感谢。

最佳答案

“但尝试访问 Base_B* pointer_,它不存在”

如果DerivedA没有正确初始化BaseA,那么DerivedA不满足继承的“isA”规则,设计需要改变。从表面上看:

  1. 不要在派生类中重复使用名称,例如 b_pointer_。它只是令人困惑,你没有任何值(value)。
  2. 使 init() 成为虚拟的。
  3. 让 DerivedA::init() 显式调用 BaseA::init()。
  4. 使 pointer_ 成为虚方法。

注意虚拟方法使用“协变返回类型”。

class BaseA
{
public:
virtual BaseB* pointer() { return &b_; }
// etc.
};

class DerivedA : public BaseA
{
public:
virtual DerivedB* pointer() { return &b_; }
// etc.
};

关于C++继承指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6673019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com