我想在课堂上制作一些Hirarchy。
示例:
object.position.x
我希望能够将Vector3类重用于速度和其他东西,这就是为什么我想将它保持为类。
我试过这样的方式。
#include"Vector3.h"
class object{
public:
Vector3 position;
Vector3 velocity;
}
-------------------------------------
class Vector3{
float x;
float y;
float z;
}
但它看起来并没有像我预期的那么好。
当我选择go.position.x = 0
代码块时,我希望我使用->
。
request for member 'x' in 'go.GameObject::position', which is of pointer type 'Vector3*' (maybe you meant to use '->' ?)|
但是当我使用它们时go.position -> x = 0
,程序崩溃了。
有人能告诉我这样做的“正确”或更好的方法是什么?
答案 0 :(得分:2)
您粘贴的代码不完整,您获得的错误似乎来自不同版本的代码。以下是使用带有和不带指针的类的示例。
#include <iostream>
using namespace std;
class Vector3{
public:
float x;
float y;
float z;
};
class Object {
public:
Vector3 position;
Vector3 velocity;
};
class ObjectPointer {
public:
Vector3 *positionPtr;
Vector3 *velocityPtr;
ObjectPointer()
: positionPtr(new Vector3()),
velocityPtr(new Vector3())
{
}
};
int main() {
// your code goes here
Object obj;
obj.position.x = 1;
obj.position.y = 2;
obj.position.z = 3;
obj.velocity.x = 11;
obj.velocity.y = 12;
obj.velocity.z = 13;
std::cout << "Object Position (" << obj.position.x
<< ", " << obj.position.y
<< ", " << obj.position.z << ")" << std::endl;
std::cout << "Object Velocity (" << obj.velocity.x
<< ", " << obj.velocity.y
<< ", " << obj.velocity.z << ")" << std::endl;
ObjectPointer *objPtr = new ObjectPointer();
objPtr->positionPtr->x = 5;
objPtr->positionPtr->y = 6;
objPtr->positionPtr->z = 7;
objPtr->velocityPtr->x = 15;
objPtr->velocityPtr->y = 16;
objPtr->velocityPtr->z = 17;
std::cout << "ObjectPointer Position (" << objPtr->positionPtr->x
<< ", " << objPtr->positionPtr->y
<< ", " << objPtr->positionPtr->z << ")" << std::endl;
std::cout << "ObjectPointer Velocity (" << objPtr->velocityPtr->x
<< ", " << objPtr->velocityPtr->y
<< ", " << objPtr->velocityPtr->z << ")" << std::endl;
return 0;
}
答案 1 :(得分:0)
由于默认情况下类的成员是私有的,因此无法像position.x那样访问它们。你需要为它们编写getter和setter,否则就像它一样构造。
structVector3{
float x;
float y;
float z;
};