Methods outside Class's scope

Hi all,

why are the bolded methods outside, and what effect has this approach?
Also, why are operator+ and operator- methods followed by const and again, what effect does this bring?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#ifndef VEC_H
#define VEC_H

#include <windows.h>

class Vec
{
public:
	Vec();
	Vec(float s, float t);

	Vec operator+(const Vec2& rhs)const;
	Vec operator-(const Vec2& rhs)const;
	Vec operator-();

	void operator+=(const Vec2& rhs);
	void operator-=(const Vec2& rhs);
	void operator*=(float b);
	void operator/=(float b);

};

Vec operator*(const Vec2& a, float b);
Vec operator*(float b, const Vec2& a);
Vec operator/(const Vec2& a, float b);
Vec operator/(float b, const Vec2& a);

#endif // VEC_H 
Anyone?
closed account (zb0S216C)
Claimz wrote:
why are the bolded methods outside, and what effect has this approach?

By overloading these operators, you're telling the compiler how it should handle the specified operands when they are used with the operators.

Note that if the same operator was overloaded within a class, the operator that resides within the class has a higher precedence over the globally overloaded operators.

Claimz wrote:
why are operator+ and operator- methods followed by const and again, what effect does this bring?

When const follows a member function definition, it means any non-mutable member cannot be modified by the member function. These are called read-only member functions. These member functions, however, can invoke any read-only member function, and can modify mutable members. In a nutshell, they are member functions that promise not to alter anything.

Edit: C++ doesn't have methods, only member functions.

Wazzak
Last edited on
Vec operator/(float b, const Vec2& a); It should be obvious that this can't be a method. (if it were it should be inside class float)

Also you can use metaprogramming that way. You just need to define the compound assignment operators (you should return a reference to *this, btw)
1
2
3
4
5
template<class T>
T operator+(const T& a, const T& b){
  T result(a);
  return result += b;
}


¿Vec2 is Vec, right?
Topic archived. No new replies allowed.