'How to use Class? (with poor English ability)
Code that implements Vectors as Class and inputs and outputs them as txt files.
I was temporarily implementing a function of Class, but I have a question because there is an error.
I tried to add vectorA and vectorB as Add functions in the main function and replace them with vectorO to printf.
However, in the Vector output part of the Add function, the error No default creator of the Vector class continues to appear. How should we solve this problem?
#include<stdio.h>
class Vector
{
public: // private?
double x, y, z;
public:
Vector(int x, int y, int z) {
x = x;
y = y;
z = z;
}
double Magnitude(void);
Vector Add(Vector v) {
Vector output;
output.x = x + v.x;
output.y = y + v.y;
output.z = z + v.z;
return output;
}
Vector Subract(Vector v);
double DotProduct(Vector v);
Vector CrossProduct(Vector v);
};
int main()
{
Vector vectorA(1, 2, 3);
Vector vectorB(4, 5, 6);
Vector vectorO = vectorA.Add(vectorB);
printf("(%d, %d, %d)\n", vectorO.x, vectorO.y, vectorO.z); // (5, 7, 9)
return 0;
}
Even if I put this code in the Vector class, I get a strange value.
Vector() {
x = x;
y = y;
z = z;
}
Solution 1:[1]
This should fix your errors. have a basic and an overrided contructors, also be careful of the variable names they shouldn't be the same
#include<stdio.h>
class Vector
{
public: // private?
double x, y, z;
public:
Vector() {
x = 0;
y = 0;
z = 0;
}
Vector(int _x, int _y, int _z) {
x = _x;
y = _y;
z = _z;
}
double Magnitude(void);
Vector Add(Vector v) {
Vector output;
output.x = x + v.x;
output.y = y + v.y;
output.z = z + v.z;
return output;
}
Vector Subract(Vector v);
double DotProduct(Vector v);
Vector CrossProduct(Vector v);
};
int main()
{
Vector vectorA(1, 2, 3);
Vector vectorB(4, 5, 6);
Vector vectorO = vectorA.Add(vectorB);
printf("(%d, %d, %d)\n", vectorO.x, vectorO.y, vectorO.z); // (5, 7, 9)
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dean Van Greunen |
