我希望能够创建一个具有 3 个 float (x,y,z) 的类型。我试过:
typedef struct
{
float x;
float y;
float z;
} Vertex;
但这没有用。
是否必须在 main
可以看到的地方声明它?我将如何为我创建的类型创建 getter 方法和其他方法?
最佳答案
我将如何在 C++ 中执行此操作。有关示例用法,请参见 main()。 注意这尚未经过编译或测试。
#include <iostream>
class Vertex
{
public:
// Construction
Vertex(float x,float y, float z) : x_(x), y_(y), z_(z) {}
// Getters
float getX() const {return x_;}
float getY() const {return y_;}
float getZ() const {return z_;}
// Setters
void setX(float val) {x_ = val;}
void setY(float val) {y_ = val;}
void setZ(float val) {z_ = val;}
private:
float x_;
float y_;
float z_;
};
int main()
{
Vertex v(6.0f,7.2f,3.3f);
v.setZ(7.7f);
std::cout < "vertex components are " << v.getX() << ',' << v.getY() << ',' << v.getZ() << std::endl;
}
关于c++ - 创建我自己的 'data type',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4450918/