我有一个关于Enumerable.Repeat函数的问题.
如果我有课:
class A
{
//code
}
Run Code Online (Sandbox Code Playgroud)
我将创建一个该类型对象的数组:
A [] arr = new A[50];
Run Code Online (Sandbox Code Playgroud)
接下来,我将要初始化这些对象,调用Enumerable.Repeat:
arr = Enumerable.Repeat(new A(), 50);
Run Code Online (Sandbox Code Playgroud)
这些对象在内存中是否具有相同的地址?如果我想检查他们的哈希码,例如以这种方式:
bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();
Run Code Online (Sandbox Code Playgroud)
这将返回true,如果我将更改一个对象属性,则所有其他对象也将更改它.
所以我的问题是:是否正确地初始化引用类型对象?如果没有,那么更好的方法是什么?
我有课:
class IComponent{};
Run Code Online (Sandbox Code Playgroud)
我将其用作其他特定类的基类.
class First : public IComponent{public: void First();};
class Second : public IComponent{public: void Second();};
Run Code Online (Sandbox Code Playgroud)
我有一个类Object,它有一个存储从IComponent继承的类的向量.
vector<IComponent*> vectorOfComponents;
Run Code Online (Sandbox Code Playgroud)
在这个类中,我有一个模板方法,可以向vector添加组件.
template<typename comp>
void AddComponent() {
comp * c = new comp();
getComponents().push_back(c);
}
Run Code Online (Sandbox Code Playgroud)
但是我也希望能够获得特定类型的组件,所以我创建了这个方法:
template<typename comp>
comp * GetComponent()
{
comp component;
for (int i = 0; i < GetComponentsCount(); i++)
if (typeid(*getComponents()[i]).name() == typeid(component).name())
return (comp*)getComponents()[i];
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
当我以后运行它:
if (obj.GetComponent<FirstClass>() != NULL)
std::cout << "isn't null\n";
else
std::cout << "is null\n";
Run Code Online (Sandbox Code Playgroud)
我知道vector可以保存IComponent继承类的推送实例,但它总是打印我为null,因为第一个typeid()显示我的IComponent,第二个显示我特定的继承组件.
如何从向量中获取特定类型?我试过多态,但是没有用,或者我做错了什么:
template<typename comp> …Run Code Online (Sandbox Code Playgroud)