浙大 C++
运算符重载-基本规则
运算符重载的含义
- Allows user-defined types to act like built in types
- Another way to make a function call.
所谓运算符重载,可以写函数去改变运算符的行为;
当运算符对你定义的那个类进行运算时,它可以不使用默认的运算逻辑。
哪些运算符可以被重载
不能重载的运算符有:
Restrictions 约束
- Only existing operators can be overloaded (you can't create a ** operator for exponentiation)
- Operators must be overloaded on a class or enumeration type
- Overloaded operators must
- Preserve number of operands
- Preserve precedence
运算符重载
How to overload
- As member function
- Implicit first argument
- No type conversion performed on receiver
- Must have access to class definition
Operators as member functions
class Integer
{
private:
int v;
public:
Integer(int n = 0) : v(n){};
const Integer operator+(const Integer& n)const{
return Integer(v + n.v);
}
void print(){cout << "value:" << v << endl;}
};
int main()
{
Integer x(100);
Integer y(25);
Integer z = x+y;
z.print();
}
member functions
x
global operators
Tip: Members vs. Free Functions
原型
Argument Passing
Return Values
The prototypes of operators
operators ++ and --
using thr overload ++ and --
Relational operators
Operator []
赋值
#include <iostream>
using namespace std;
class A
{
public:
A() {}
};
class B
{
public:
B(int) {}
B(const A &) {}
};
// g++ main.cpp && ./a.out
// g++ main.cpp -o maincpp.out && ./maincpp.out
int main()
{
B b1 = 1;
A a;
B b2 = a;
b2 = a;
return 0;
}
Automatic operator= creation
#include <iostream>
using namespace std;
class A
{
public:
A &operator=(const A &)
{
cout << "inside A::operator=()" << endl;
return *this;
}
};
class B
{
A a;
};
// g++ main.cpp && ./a.out
// g++ main.cpp -o maincpp.out && ./maincpp.out
int main()
{
B m, n;
m = n;
return 0;
}
Assignment Operator
类型转换
Values Classes
#include <iostream>
using namespace std;
class A
{
public:
A() {}
};
class B
{
public:
B(const A &) {}
};
void f(B) {}
// g++ main.cpp && ./a.out
int main()
{
A a;
f(a); // Wants a B,Has a A
return 0;
}
explicit
#include <iostream>
using namespace std;
class A
{
public:
A() {}
};
class B
{
public:
explicit B(const A &) {}
};
void f(B) {}
// g++ main.cpp && ./a.out
int main()
{
A a;
// f(a); // Not auto conversion allowed
f(B(a)); // OK
return 0;
}