gpt4 book ai didi

c++ - 如何在 C++ 中强制在另一个对象(依赖于它)中实例化一个对象

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

我掌握了这种情况:

  1. 对象 A 依赖于一个或多个对象 B(及其后代)。
  2. 对象 A 和 B 可以有多个实例。应该将它们插入列表中的某处(B 对象的列表以 vector 形式存在于拥有它们的对象 A 中)。
  3. 对象 B(及其后代)不能存在于另一个对象和专用于对象 A 的唯一对象中。
  4. 因此,对象 B 不能在对象 A 之外实例化。
  5. 如果对象 A 已实例化,它可以即时创建对象 B(及其后代)的实例,并将其插入对象 B 的 vector 。
  6. 对象 A 和对象 B 都可以无限地派生出许多变体。

到目前为止,我已经提出了2个解决方案,我认为它们都不是错误的。

解决方案 #1:

Use a manager + factory class which would create and pair both object A and B. Which also will manage the list / vector of object A.

这个的问题是:1. 我需要将 manager + factory 对象的实例大量传递给需要实例化对象 A 和 B 的任何对象。2. 因为我不确定将来会派生出多少个对象A和B的变体,所以我无法进行switch/case实例化。或者如果我们采用工厂模式方式,我必须强制对象 A 和 B 的每个子对象都应该有一对自己的工厂类。有点乏味,如果你问我,可能会使应用程序膨胀。3.不能强制执行上述规则的第3点和第4点。除非我隐藏构造函数并将它们设为私有(private)/ protected ,并将管理器 + 工厂类设为友元类。

解决方案#2:

Make object A manage itself and will store its reference into a member static vector upon creation. Object B must only be created via a method called "AddB()" which will have a template class as an input, and inside the method, it will instantiate the template class and store it into a vector of object B.

这个的问题是:1. 我无法确定输入的模板类实际上是对象 B 的子类/派生类,因为它毕竟是一个模板。2. 很有可能会增加一些性能上的冲击,因为毕竟是模板。仅供引用,我可能需要经常实例化它,甚至一次要实例化 2000 左右。3.仍不能执行上述规则的第3点和第4点。除非我隐藏构造函数并将它们设为私有(private)/ protected ,并将 A 类设为 B 类的友元类。

那么,关于如何最好地解决这个问题有什么想法吗?

提前致谢。

最佳答案

对我来说,它看起来像“因此,对象 B 不能在对象 A 之外实例化。”是问题的关键。

模板路由可能是最好的,因为如果类不是 vector 类型的子类,它会产生编译时错误。我还让每个 B(动物)类成为 A 的 friend ,这样 A 就可以使用私有(private)构造函数。它会侵 eclipse 封装,并且可能难以维护,但它确实有效。

例子:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Farm;
class Animal {
protected:
Animal() {}
public:
virtual ~Animal() {}
void makeSound() { cout << this->sound() << endl; }
virtual string sound () const = 0;
friend class Farm;
};

class Cat : Animal {
protected:
Cat() {}
public:
virtual ~Cat() {}
virtual string sound () const { return "meow"; }
friend class Farm;
};


class Dog : Animal {
protected:
Dog() {}
public:
virtual ~Dog() {}
virtual string sound () const { return "bark"; }
friend class Farm;
};

class Tractor {
protected:
Tractor() {}
virtual ~Tractor() {}
virtual string sound () const { return "rummm!"; }
friend class Farm;
};


class Farm {
vector< Animal * > animals;

public:
template< typename AnimalType >
void create() {
animals.push_back( new AnimalType );
}

void disturbAnimals() {
for( auto animal : animals ) {
animal->makeSound();
}
}
};


int main( int argc_, char ** argv_ ) {
Farm farm;
farm.create<Cat>();
farm.create<Dog>();

// Generates compile-time error
//farm.create<Tractor>();
farm.disturbAnimals();

return 0;
}

关于c++ - 如何在 C++ 中强制在另一个对象(依赖于它)中实例化一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574153/

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