gpt4 book ai didi

c++ - 基类可以有一个成员是派生类的实例吗?

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

我能否拥有一个基类,其成员是派生类的实例?我应该如何转发声明或包含派生类定义?还是我应该这样做的另一种方式?

// base.h

class DerivedClass; // Is forward declaration sufficient?

class Base {
public:
virtual ~Base();
virtual void DoStuff() = 0;
void DoSomethingWithD() {
d_.Foo();
}
protected:
DerivedClass d_;
};

// derived.h

#include "base.h"

class Derived : public Base {
public:
Derived();
void DoStuff();
void Foo();
private:
Derived(const Derived&);
void operator=(const Derived&);
};

// other_derived.h

#include "base.h"

class OtherDerived : public Base {
public:
OtherDerived();
void DoStuff();
private:
OtherDerived(const OtherDerived&);
void operator=(const OtherDerived&);
};

最佳答案

这对您有用,请参阅有关更改的评论:

#include <memory>

class Derived;

class Base {
public:
virtual ~Base();
virtual void DoStuff() = 0;
void DoSomethingWithD(); // no longer defined in-line
protected:
std::unique_ptr<Derived> d_; // storing as a pointer as Derived is still incomplete
};

class Derived : public Base {
public:
Derived();
void DoStuff();
void Foo();
private:
Derived(const Derived&);
void operator=(const Derived&);
};

class OtherDerived : public Base {
public:
OtherDerived();
void DoStuff();
private:
OtherDerived(const OtherDerived&);
void operator=(const OtherDerived&);
};

// definition moved down here where Derived is a complete type
void Base::DoSomethingWithD() {
d_->Foo();
}

关于c++ - 基类可以有一个成员是派生类的实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820182/

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