C ++规范化向量;错误:无法绑定

时间:2015-10-08 04:05:14

标签: c++ c++11 vector

#include <iostream>
#include <math.h>
using namespace std;

class Vectors
{
    public:
    Vectors(void);
    float X, Y;
    Vectors (float X, float Y);
    float magnitude();
    Vectors normalize();

};

Vectors::Vectors (float x_value, float y_value) {
    X = x_value;
    Y = y_value;
}

float Vectors::magnitude() {
    return sqrt(X * X + Y * Y);
}

Vectors Vectors::normalize() {
    Vectors my_vector;
    float length = this->magnitude();
    if(length !=0){
        my_vector.X = X/length;
        my_vector.Y = Y/length;
    }
    return my_vector;
}

int main() {
    Vectors my_vector(3.0,4.0);
    float mag_result = my_vector.magnitude();
    cout << "magnitude: " << mag_result;
    Vectors norm_result = my_vector.normalize();
    cout << "normalize: " << norm_result;
    return 0;
}

我正在尝试编写一些会返回传递给它的向量的规范化/单位向量的东西。我对C ++完全陌生,所以我无论是否正确,我都无法做到正确。我的normalize函数应该返回任何东西吗?或者它应该只是更改X和Y的值,然后我从my_vector访问它们?

这是我目前收到的错误:

In function 'int main()':
40:14: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from 1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Vectors]'
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

3 个答案:

答案 0 :(得分:1)

C ++只知道在写入cout时如何处理简单类型。您是否可以将Vectors对象直接发送到cout。相反,您需要以简单的术语发送要转储的内容。即。

矢量正常= cout&lt;&lt; &#34;标准化:&#34; &LT;&LT; norm_result.X&lt;&lt; &#34;&#34; &LT;&LT; norm_result.Y;

你可能也想把std :: endl放在你的mag_result转储的末尾。

答案 1 :(得分:0)

norm_result是类,你最好使用类Vectors的成员X,Y。

答案 2 :(得分:-2)

您最好为类向量ostream<<添加{{1}}个函数