如何使用Class? (英语能力较差)
How to use Class? (with poor English ability)
将 Vectors 实现为 Class 并将其输入和输出为 txt 文件的代码。
我临时实现了Class的一个功能,但是有一个问题,因为有错误。
我尝试在main函数中添加vectorA和vectorB作为Add函数,并用vectorO替换到printf中。
但是,在Add函数的Vector输出部分,错误No default creator of the Vector class继续出现。我们该如何解决这个问题?
#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;
}
即使我将此代码放入 Vector class,我也会得到一个奇怪的值。
Vector() {
x = x;
y = y;
z = z;
}
这应该可以解决您的错误。有一个基本的和一个重写的构造函数,还要注意变量名,它们不应该相同
#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;
}
将 Vectors 实现为 Class 并将其输入和输出为 txt 文件的代码。
我临时实现了Class的一个功能,但是有一个问题,因为有错误。
我尝试在main函数中添加vectorA和vectorB作为Add函数,并用vectorO替换到printf中。
但是,在Add函数的Vector输出部分,错误No default creator of the Vector class继续出现。我们该如何解决这个问题?
#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;
}
即使我将此代码放入 Vector class,我也会得到一个奇怪的值。
Vector() {
x = x;
y = y;
z = z;
}
这应该可以解决您的错误。有一个基本的和一个重写的构造函数,还要注意变量名,它们不应该相同
#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;
}