我有以下课程:
class Vector
{
public:
float x_;
float y_;
float z_;
Vector(float x, float y, float z) : x_(x), y_(y), z_(z) {}
float scalar(Vector a, Vector b);
};以及以下方法:
float Vector::scalar(Vector a, Vector b)
{
return a.x_ * b.x_ + a.y_ * b.y_ + a.z_ * b.z_;
}现在,我在主函数中初始化Vector a和Vector b:
int main()
{
Vector a = Vector(1,2,3);
Vector b = Vector(4,5,6);
float result;
// how can I call the scalar() method and save the return value in result
return 0;
}但是现在我想知道如何调用标量()方法。我试图声明标量()是静态的,但是它没有工作。
发布于 2018-07-01 09:34:56
您可以做的是将您的方法创建为静态方法。它将产生与用类名为您的方法命名空间相同的效果。
class Vector
{
public:
float x_;
float y_;
float z_;
Vector(float x, float y, float z) : x_(x), y_(y), z_(z) {}
static float scalar(Vector a, Vector b);
};您可以在主目录中调用以下方式:
int main()
{
Vector a = Vector(1,2,3);
Vector b = Vector(4,5,6);
float result = Vector::scalar(a, b);
return 0;
}发布于 2018-07-01 09:42:58
与其他语言不同,C++允许您拥有非类成员的函数。您可以在向量之外定义函数,然后在没有对象前缀的情况下调用它。
class Vector
{
public:
float x_;
float y_;
float z_;
Vector(float x, float y, float z) : x_(x), y_(y), z_(z) {}
};
float scalar(Vector a, Vector b)
{
return a.x_ * b.x_ + a.y_ * b.y_ + a.z_ * b.z_;
}
int main()
{
Vector a(1,2,3);
Vector b(4,5,6);
float result = scalar(a, b);
return 0;
}发布于 2018-07-01 09:35:25
您需要将标量定义为静态,并将其称为静态方法:
class Vector
{
...
static float scalar(Vector a, Vector b);
};和
auto result = Vector::scalar(a,b);https://stackoverflow.com/questions/51122055
复制相似问题