I created a class "vector" that just return x,y,z values. But when I try to get a value from the class and print it, it said 0 instead of the expected value. I've tried this apart from my visual studio project and it worked so Im totally lost. I put this in main function to simplify but actually I use WinMain.
vector.h
#ifndef VECTOR_H
#define VECTOR_H
class vector {
public:
//declaration
double x, y, z;
vector(double x, double y, double z);
};
vector.cpp
#include "vector.h"
//definition
vector::vector(double x, double y, double z) : x(x), y(y), z(z) {}
main.cpp
int main() {
//create a array of vector
vector vertices[4] = {
vector(0, 0, 0),
vector(1, 0, 0),
vector(1, 1, 0),
vector(0, 1, 0),
};
std::cout << vertices[1].x << std::endl;
//and it prints 0 instead of 1;
return 0;
}
My interpretation is you want to create vector of user defined class which has 3 members as x, y, z
So, below is code which you can refer and modify as required.
class myClass{
public:
double x, y, z;
myClass() { x = 0.0; y = 0.0; z = 0.0; };
myClass(double x, double y, double z) : x(x), y(y), z(z) {}
};
int main() {
vector <myClass>vertices = {
myClass(0, 0, 0),
myClass(1, 0, 0),
myClass(1, 1, 0),
myClass(0, 1, 0),
};
std::cout << vertices[1].x << std::endl;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.