个人的关于c++运算符重载的总结

1.重载的运算符必须是成员函数吗?

不必。重载的运算符不必是成员函数,但必须至少有一个操作数是用户定义的类型。

一般来说,非成员函数可以定义成友元函数以访问类的私有成员

也可以不定义为友元函数

2.哪些运算符不能被重载?

sizeof
.  (成员运算符)
.* (成员指针运算符)
:: (域运算符)
?:(条件运算符)
typeid
dynamic_cast
static_cast
const_cast
reinterpret_cast

3.".*"是什么(成员指针运算符)

class A
{
public:
	int a;
	A(int a = 0) {}
};

int main()
{
	int A::*p1 = &A::a;
	A a;
	a.*p1 = 1;
	cout << a.a << endl;
	return 0;
}

4.a++ 与++a的重载

a++相当于

operator ++(int)

++a 相当于

operator ++() 

下面是一个例子

class C
{
public:
	int val;
	C(int x): val(x) {}
	C& operator++() { 
		cout << "operator ++" << endl;
		val++; return *this; }
	C& operator++(int) 
	{ 
		cout << "operator ++int " << endl;
		val++; return *this; 
	}
};

int main()
{
	C c(1);
	++c;
	c++;
	return 0;
}

结果:

operator ++
operator ++int

5.运算符重载有什么特点?

1.有些运算符不能被重载
2.不能改变优先级和结合性,不能改变用法
3.不能创造运算符
4.重载后必须有一个至少有一个操作数是用户定义的类型
5.下面的运算符只能通过成员函数来重载
=
[]
()
->
6.参数不能有默认值,比如不能写operator++(int a = 0),这个不对

6.箭头运算符的重载

如果point是一个定义了operator->() 的类对象,
则point->member等价于point.operator->() ->member

下面的例子:

class firstClass {
public:
	firstClass* operator->() {
		std::cout << "firstClass ->() is called!" << std::endl;
		return this;
	}
	void action() {
		std::cout << "firstClass action() is called!" << std::endl;
		return;
	}
};

class myClass {
	firstClass firstObj;
public:
	firstClass& operator->() {
		std::cout << "myClass ->() is called!" << std::endl;
		return firstObj;
	}
	void action() {
		std::cout << "myClass action() is called!" << std::endl;
		return;
	}
};

int main() {
	myClass obj;
	obj->action();

	return 0;
}

结果:

myClass ->() is called!
firstClass ->() is called!
firstClass action() is called!
发布了81 篇原创文章 · 获赞 4 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/m0_37313888/article/details/105234700
今日推荐