在main方法中将三维矢量乘以标量 p>我对C++非常陌生,IM试图用标量乘以向量。< /P>

在main方法中将三维矢量乘以标量 p>我对C++非常陌生,IM试图用标量乘以向量。< /P>,c++,vector,C++,Vector,我的vector3D.h文件中的代码: //multiply this vector by a scalar Vector3D operator*(float num) const { return Vector3D(x * num, y * num, z * num); } 主要功能: int scalar = 2; Vector3D*vector1 = new Vector3D(1,2,4); cout << " Vector multiplcation by scal

我的vector3D.h文件中的代码:

//multiply this vector by a scalar
Vector3D operator*(float num) const
{
    return Vector3D(x * num, y * num, z * num);
}
主要功能:

int scalar = 2;
Vector3D*vector1 = new Vector3D(1,2,4);
cout << " Vector multiplcation by scalar ";
cout << vector1*scalar;
int标量=2;
Vector3D*vector1=新的Vector3D(1,2,4);

cout表达式中的向量1
之前缺少解引用运算符
*
。您需要它,因为
vector1
本身不是
Vector3D
本身,它只是一个指针


此外,您应该记住,С++与java不同。在您的情况下,
new
是完全冗余和不安全的(如果您忘记删除它,可能会导致内存泄漏)。这里是简单的
Vector3D向量1(1,2,4)就足够了。此外,如果您使用此选项,您不需要额外的
*

HolyBlackCat有一些好的评论,您应该遵循它们。以下是一个最低限度的工作示例:

#include <iostream>
using namespace std;

class Vector3D {
public:
    Vector3D(double x, double y, double z): x(x), y(y), z(z) {}

    Vector3D operator*(double num) const {
        return Vector3D(x*num, y*num, z*num);
    }

    void print() {
        cout << "(" << x << ", " << y << ", " << z << ")" << endl;
    }

private:
    double x, y, z;
};


int main() {
    int scalar = 2;
    Vector3D vector1(1, 2, 4);
    cout << "Vector multiplcation by scalar: ";
    Vector3D vector2 = vector1*scalar;
    vector2.print();
}
#包括
使用名称空间std;
类向量3D{
公众:
向量3d(双x,双y,双z):x(x),y(y),z(z){}
Vector3D运算符*(双数值)常量{
返回向量3d(x*num,y*num,z*num);
}
作废打印(){

为什么
vector1
是一个指针?使用这个指针不是不正确的,但是您的答案是正确的,它是不需要的。我相应地修改了我的答案。