gpt4 book ai didi

c++ - 涉及内部类的继承 C++

转载 作者:行者123 更新时间:2023-11-28 07:13:57 26 4
gpt4 key购买 nike

我对继承的概念很陌生,因此我有一个问题。想象一下,我有这样一个类:

class A{
protected:
class B{
int x;
B() : x(3){}
int g(int y) {return x*y;}
friend class A;
};
B *b;
public:
int f(int y) {return b->g(y);}
};

我想继承类 A,不是覆盖方法 f,而是覆盖 f 正在调用的方法 g,以便 f 在派生类中的工作方式不同。我怎么能那样做?

最佳答案

您还需要指定构造函数,在本例中为类 A 的复制运算符是强制性的。让我们假设您的构造函数之一如下所示:

A::A()
{
b = new B;
}

然后你需要做的是在从A派生的类的构造函数中用一个指向从B派生的类的指针替换b:

class C : public A
{
protected:
class D : public B
{
int z;
public:
D() : z(27) { }
int g(int y) { return z + y;}
};

public:
C()
{
// Delete pointer to B created by the parent class constructor that
// executes just before this constructor.
delete b;
// Point b to an instance of D; possible because D is derived from B.
b = new D;
}
};

请记住,对于这样的操作,您需要实现所有构造函数、复制运算符和析构函数。

关于c++ - 涉及内部类的继承 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532373/

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