我正在尝试编写一个 Unity 风格的获取组件方法。这是我到目前为止的代码。它会编译,但会返回它找到的第一个组件,而不是正确的组件。我认为我使用 static_cast 是错误的。有什么更好的方法来做到这一点?请注意,我不想对组件类型进行硬编码,我希望能够编译此引擎并使用从 Component 继承的任何内容以便能够使用此系统。另请注意,每个组件都需要作为其自身返回,而不是组件*,因为这会隐藏子功能。
compStruct.components 是组件 *s 的向量。
template <typename CompType>
inline CompType getComponent()
{
for(Component * currComp : compStruct.components)
{
if (static_cast<CompType>(currComp)!= nullptr)
{
return static_cast<CompType>(currComp);
}
}
return nullptr;
}
Run Code Online (Sandbox Code Playgroud)
这是通用组件的示例
#pragma once
#include "Component.h"
#include "Animation2D.h"
class AnimationComponent : public Component
{
public:
AnimationComponent(GameObject*x) :Component(x) {}
~AnimationComponent() {}
void stepAnimation(double delta);
//add overload for 3d animations
int addAnimation(Animation2D);
void setAnimation(int);
private:
};
Run Code Online (Sandbox Code Playgroud)
以及组件基类:
#pragma once
class GameObject;
class Component
{
public:
Component(GameObject * h) …Run Code Online (Sandbox Code Playgroud) 以下是安全的吗?
unordered_map<string, string> my_map;
unordered_map<string, double> new_map;
for(auto&& [key, value] : my_map) {
new_map.insert({std::move(key), std::stod(value)});
}
Run Code Online (Sandbox Code Playgroud)
我没有my_map在循环之后使用,是否可以从key迭代中移动它?
我试图理解为什么在调用时没有为此类定义的运算符(<)被执行:
//File A.h (simplified class)
#ifndef __A__H
#define __A__H
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
class A {
private:
string _str;
int _number;
public:
A( string str="", int age=0): _str(str), _number(number){} //inline
int operator < (const A &a1 ) const
{
cout<<"Call of new operator <"<<endl;
if ( _str == a1._str )
return _number < a1._number;
return _str < a1._str; //here use of (<) associated to string
}
};
#endif
int main()
{
A *obj1= new A("z",10); …Run Code Online (Sandbox Code Playgroud) static void func1(){
static int i(9);
};
Run Code Online (Sandbox Code Playgroud)
是否在调用函数或程序启动时为静态变量 i 分配了内存?