- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我掌握了这种情况:
到目前为止,我已经提出了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/
我是一名优秀的程序员,十分优秀!