rab*_*bit 1 c++ operator-overloading
我最近尝试过运算符重载,并查看了有关运算符重载的此stackoverflow页面(http://stackoverflow.com/questions/4421706/operator-overloading).
我重载了*运算符,可以运行代码如
Vector2 a(2, 3);
Vector2 b(5, 8);
Vector2 c = a*b;
Run Code Online (Sandbox Code Playgroud)
但得到编译时错误 error: invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'Vector2')
运行代码时如
std::cout << a*b;
Run Code Online (Sandbox Code Playgroud)
这是Vector2.cpp
#include "Vector2.h"
Vector2::Vector2(const float x, const float y) {
this->x = x;
this->y = y;
}
Vector2 &Vector2::operator*=(const Vector2 &rhs) {
this->x *= rhs.x;
this->y *= rhs.y;
return *this;
}
std::ostream &operator<< (std::ostream &out, Vector2 &vector) {
return out << "(" << vector.x << ", " << vector.y << ")";
}
Run Code Online (Sandbox Code Playgroud)
这是Vector2.h
#include <iostream>
class Vector2 {
public:
float x;
float y;
Vector2(const float x, const float y);
Vector2 &operator*=(const Vector2 &rhs);
};
inline Vector2 operator*(Vector2 lhs, const Vector2 &rhs) {
lhs *= rhs;
return lhs;
}
std::ostream &operator<<(std::ostream &out, Vector2 &vector);
Run Code Online (Sandbox Code Playgroud)
我不知道从哪里开始.
问题是
a*b
Run Code Online (Sandbox Code Playgroud)
返回一个临时的,所以你需要:
std::ostream &operator<<(std::ostream &out, const Vector2 &vector);
// |
// notice const
Run Code Online (Sandbox Code Playgroud)
作为临时不能绑定到非const引用.
| 归档时间: |
|
| 查看次数: |
2579 次 |
| 最近记录: |