2016-11-08 34 views
1

我对C++非常陌生,我试图用标量乘以向量。用主要方法中的标量乘以3D向量

的代码在我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; 

我明白这是完全地错误的,但我不知道我怎么会使用上面的功能。

给出的错误是表达式必须有算术或无范围的枚举类型。

感谢

+0

为什么'vector1'是一个指针? – NathanOliver

回答

2

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(); 
} 

注意额外的print()方法。如果你想做类似cout < <的vector1 *标量,那么你还需要做一些额外的工作来定义ostream如何处理Vector3D对象。

+1

这个指针是没有错的,但是你的正确性是不需要的。我相应地修改了我的答案。 –

1

你错过了对其操作*在表达vector1之前。你需要它,因为vector1本身不是Vector3D,它只是一个指针。

另外,你应该记住С++不像java。在你的情况下,new是完全冗余和不安全的(如果你忘记删除它,可能会导致内存泄漏)。这里简单的Vector3D vector1(1, 2, 4);就够了。此外,如果您使用此替代方案,则不需要额外的*