使用 void 指针数组时出现 C++ 错误
C++ error when using array of void pointers
我想在 GameObject
class 中包含一个继承自 A
class 的对象向量,以及一个模板方法,它将添加模板的新对象输入向量。
但我想有可能使用参数类型未知的构造函数,所以我想使用 void 指针数组来做到这一点,但我有一个错误提示:
exited with non-zero status
代码如下:
#include <iostream>
#include <string>
#include <vector>
class A
{
public:
virtual void whatever() { std::cout << "okay\n"; }
};
class B : public A
{
public:
float a;
std::string b;
int c;
void print()
{
std::cout << "a,b,c values: " << a << ", " << b << ", " << c << std::endl;
}
B(void * parameters[])
{
this->a = *(static_cast<float*>(parameters[0]));
this->b = *(static_cast<std::string*>(parameters[0]));
this->c = *(static_cast<int*>(parameters[0]));
}
};
class GameObject
{
public:
std::vector<A*> components{};
template<class T>
void AddComponent(void * parameters[])
{
auto t = new T(parameters);
components.push_back(t);
}
};
int main()
{
float f = 2524.218f;
std::string s = "str";
int i = 4214;
auto g = new GameObject;
void* ptr[3];
ptr[0] = &f;
ptr[1] = &s;
ptr[2] = &i;
g->AddComponent<B>(ptr);
static_cast<B*>(g->components[0])->print();
}
你能告诉我问题出在哪里吗?如果可能的话,请更正代码?
this->a = *(static_cast<float*>(parameters[0]));
this->b = *(static_cast<std::string*>(parameters[0]));
this->c = *(static_cast<int*>(parameters[0]));
您的意思是:
this->a = *(static_cast<float*>(parameters[0]));
this->b = *(static_cast<std::string*>(parameters[1]));
this->c = *(static_cast<int*>(parameters[2]));
即使用不同的数组索引。
我想在 GameObject
class 中包含一个继承自 A
class 的对象向量,以及一个模板方法,它将添加模板的新对象输入向量。
但我想有可能使用参数类型未知的构造函数,所以我想使用 void 指针数组来做到这一点,但我有一个错误提示:
exited with non-zero status
代码如下:
#include <iostream>
#include <string>
#include <vector>
class A
{
public:
virtual void whatever() { std::cout << "okay\n"; }
};
class B : public A
{
public:
float a;
std::string b;
int c;
void print()
{
std::cout << "a,b,c values: " << a << ", " << b << ", " << c << std::endl;
}
B(void * parameters[])
{
this->a = *(static_cast<float*>(parameters[0]));
this->b = *(static_cast<std::string*>(parameters[0]));
this->c = *(static_cast<int*>(parameters[0]));
}
};
class GameObject
{
public:
std::vector<A*> components{};
template<class T>
void AddComponent(void * parameters[])
{
auto t = new T(parameters);
components.push_back(t);
}
};
int main()
{
float f = 2524.218f;
std::string s = "str";
int i = 4214;
auto g = new GameObject;
void* ptr[3];
ptr[0] = &f;
ptr[1] = &s;
ptr[2] = &i;
g->AddComponent<B>(ptr);
static_cast<B*>(g->components[0])->print();
}
你能告诉我问题出在哪里吗?如果可能的话,请更正代码?
this->a = *(static_cast<float*>(parameters[0]));
this->b = *(static_cast<std::string*>(parameters[0]));
this->c = *(static_cast<int*>(parameters[0]));
您的意思是:
this->a = *(static_cast<float*>(parameters[0]));
this->b = *(static_cast<std::string*>(parameters[1]));
this->c = *(static_cast<int*>(parameters[2]));
即使用不同的数组索引。