c_cpp C ++中的运算符重载

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C ++中的运算符重载相关的知识,希望对你有一定的参考价值。

**Defination** : Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.

1. Java does not support operator overloading, except for string concatenation for which it overloads the + operator internally.
2. In C++, we can make operators to work for user defined classes. For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +.
3. Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.
4. Following operator cannot be overloaded
  >. (dot) 
  >:: 
  >?: 
  >sizeof 
  [Why?](http://www.stroustrup.com/bs_faq2.html#overload-dot)

**Rules for Operator Overloading**

1. Only built-in operators can be overloaded. New operators can not be created.
2. Arity of the operators cannot be changed.
3. Precedence and associativity of the operators cannot be changed.
4. Overloaded operators cannot have default arguments except the function call operator () which can have default arguments.
5. Operators cannot be overloaded for built in types only. At least one operand must be used defined type.
6. Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must be defined as member functions
7. Except the operators specified in point 6, all other operators can be either member functions or a non member functions.
8. Some operators like (assignment)=, (address)& and comma (,) are by default overloaded.
#include <iostream>
using namespace std;

class Complex {
	private:
		int real, imag;
	public:
		Complex(int r = 0, int i = 0) { real = r, imag = i; }
		void print() { cout << real << " + i" << imag << endl; }
		
		// The global operator function is made friend of this class so
		// that it can access private members
		friend Complex operator + (Complex const &, Complex const &);
};
Complex operator + (Complex const &c1, Complex const &c2){
	return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main() {
	Complex c1(10, 2), c2(2, 3);
	Complex c3 = c1 + c2;
	c3.print();
	return 0;
}
#include <iostream>
using namespace std;

class Complex {
	private:
		int real, imag;
	public:
		Complex(int r = 0, int i = 0) { real = r, imag = i; }
		// This is automatically called when '+' is used with
		// between two Complex objects
		Complex operator + (Complex const &obj){
			Complex res;
			res.real = real + obj.real;
			res.imag = imag + obj.imag;
			return res;
		}
		void print() { cout << real << " + i" << imag <<endl; }
};

int main() {
	Complex c1(10, 2), c2(2, 4);
	Complex c3 = c1 + c2;
	c3.print();
	return 0;
}

以上是关于c_cpp C ++中的运算符重载的主要内容,如果未能解决你的问题,请参考以下文章

C/C++编程笔记:C++中的函数重载

C/C++编程笔记:C++中的运算符重载

c_cpp C / C ++中的链表示例

c_cpp C中的功能

c_cpp C中的评论

c_cpp C中的关系运算符