当前位置: 代码网 > it编程>编程语言>C/C++ > 探究C++中指针与数组运算符优先级

探究C++中指针与数组运算符优先级

2024年10月06日 C/C++ 我要评论
c++中与指针和数组相关的运算符优先级,通过实际代码示例解释了运算符的左结合与右结合方式,以及如何使用圆括号()来改变默认的结合顺序,文章还提供了一个优先级表,列出了运算符的优先级和结合性,帮助读者更

c++中与指针和数组相关的运算符优先级,通过实际代码示例解释了运算符的左结合与右结合方式,以及如何使用圆括号()来改变默认的结合顺序,文章还提供了一个优先级表,列出了运算符的优先级和结合性,帮助读者更好地理解复杂表达式中运算符的调用顺序,特别对于同时存在左结合和右结合运算符的情况,给出了详细的分析和示例,使读者能够深入理解运算符优先级的实际应用

指针、数组相关的运算符优先级

下表展示了相关运算符的优先级,有4个级别,同级别内的运算符按照结合性依次调用。这4类也是所有运算符中优先级最高的4档,其它的运算符优先级都比它们低:

优先级运算符描述结合性
1::作用域解析左结合
2()
[]
.
->
强制运算结合,函数形参列表
数组元素下标访问
类的成员访问
类指针的成员访问
右结合
3(int)
*
&
强制转换
指针解引用
变量取地址
左结合
4.*
->*
类的成员函数指针
类指针的成员函数指针
左结合

容易产生困惑的、需要仔细进行优先级判断的往往是一个左结合加一个右结合,例如:

  • *ptr[]
  • (int)a()
  • &obj->data
  • obj->*fun()

请记住一个重要方法:当我们需要改变运算符的结合顺序(c++默认的优先级不是我们的意愿)时,可以通过添加()来人为强制指定优先顺序,因为()是除了::以外具有最高优先级的一类运算符。

简单例子:以[]和*为例探讨运算符结合规律

下面的p1, p2是数组,p3是指针:

int *p1[2];    // p1是一个数组,元素个数为2,每个元素为(int*)
int *(p2[2]);  // 等价于*p2[2],p2是一个数组
int (*p3)[2];  // p3是一个指针,指向一个int数组,这个int数组的元素个数必须是2!

因此只要记住两点即可:

  • []的优先级高于*:即*p1[2]*(p1[2])等价。
  • 这个优先级同时适用于定义语句(*为指针定义符)执行语句(*为解引用符)中:
int *p1[2];    // 定义语句:先看[]:p1是一个数组,元素个数为2,每个元素为(int*)。等价于*(p1[2])
int (*p2)[2];  // 定义语句:先看*: p2是一个指针,指向一个int数组,这个int数组的元素个数必须是2!
cout << "*p1[0] = " << *p1[0] << endl;     // 执行语句:先看[]:先取第0个元素,再解引用。等价于*(p1[0])
cout << "(*p2)[0] = " << (*p2)[0] << endl; // 执行语句:先看*:先解引用,再取第0个元素

完整示例:

#include <iostream>
using namespace std;

int main(){	
	// []的优先级高于*,因此下面的p1是数组,p2是指针:
	int *p1[2];    // p1是一个数组,元素个数为2,每个元素为(int*)。等价于*(p1[2])
	int (*p2)[2];  // p2是一个指针,指向一个int数组,这个int数组的元素个数必须是2!
	int a = 1, b = 2;
	int c[2] = {4,5};
	p1[0] = &a;
	p1[1] = &b;
	p2 = &c;
	cout << "*p1[0] = " << *p1[0] << endl;
	cout << "*p1[1] = " << *p1[1] << endl;
	cout << "*(p1[0]) = " << *(p1[0]) << endl;  // 与上面两条等价
	cout << "*(p1[1]) = " << *(p1[1]) << endl;
	cout << "(*p2)[0] = " << (*p2)[0] << endl;  
	cout << "(*p2)[1] = " << (*p2)[1] << endl;
	
	return 0;
}

输出:

*p1[0] = 1
*p1[1] = 2
*(p1[0]) = 1
*(p1[1]) = 2
(*p2)[0] = 4
(*p2)[1] = 5

复杂例子:探讨当左结合和右结合运算符同时存在时如何界定优先级

下面的例子比较复杂,需要耐心仔细阅读和体会。如果这个例子能搞清楚,那么相信你对运算符优先级的理解将会上升一个档次。

这个例子研究了当左结合和右结合运算符同时存在时的结合顺序,同时也演示了可以使用()强制人为指定结合顺序:

#include <iostream>
#include <string>
using namespace std;

class student{
public:
	student(string name, int id):_name(name),_id(id){}
	void printinfo(){
		cout << "i am a student. my name is " << _name << ". my id is " << _id << endl;
	}
	void operator()(){
		printinfo();
	}
protected:
	string _name;
	int _id;
};

class student2 : public student{
public:
	student2(string name, int id):student(name, id){}
	void printinfo(){
		cout << "i am a super student!!! " << endl;
	}
	void operator()(){
		cout << "i am student2!!!" << endl;
	}
};

struct studentwrapper{
	student* _ps;
	studentwrapper(student* ps):_ps(ps){}
	student* operator()(){return _ps;}
};

int main(){	
	// .和(), ->和()平级:从左向右
	cout << "-----------------1------------------" << endl;
	student s1("bob",101), s2("jack", 102);
	student *ps1 = new student("eric",103);
	s1.printinfo();
	s2.printinfo();
	ps1->printinfo();

	// .高于*:先结合.
	cout << "-----------------2------------------" << endl;
	// 下面这条语句报错:先调用.printinfo(),再*,因此会报错
	// *ps1.printinfo();  // error: request for member 'printinfo' in 'ps1'
	(*ps1).printinfo(); 
			
	// .和()高于*:先结合()和.(从右向左),最后结合*
	cout << "-----------------3------------------" << endl;
	studentwrapper sw(ps1);
	// 下面这条语句报错:先结合sw(),再结合.printinfo(),最后结合*,因此会报错
	// *sw().printinfo(); // error: request for member 'printinfo' in 'sw.studentwrapper::operator()()'
	(*sw()).printinfo(); // correct:先sw(),再*sw(),再(*sw()).printinfo()
	// 下面这条语句报错:先结合sw(),再结合(),最后结合*,因此会报错
	// *sw()(); // error: expression cannot be used as a function
	(*sw())(); // correct:先sw(),再*sw(),再(*sw())()

	// (int)和()/[]:先结合()和[],再强转
	cout << "-----------------4------------------" << endl;
	student2 ss("alice", 999), sss("jason", 998), ssarray[2] = {ss, sss};
	ss();   // 调用student2::operator()
	// 下面这条语句报错,因为会先结合ss(),再强制转换
	// (student)ss(); // error: invalid use of void expression
	((student)ss)(); // correct: 调用student::operator()
	// 下面这条语句报错,因为会先结合ssarray[0], 再ssarray[0](),再强制转换
	// (student)ssarray[0](); // error: invalid use of void expression
	((student)ssarray[1])(); // correct:将ssarray[1]强制转换为student类型后,调用其()方法

	// ()高于.*和->*:先结合()
	cout << "-----------------5------------------" << endl;
	void (student::*fp)();
	fp = student::printinfo;
	// s1.*fp();   // error: must use '.*' or '->*' to call pointer-to-member function in 'fp (...)'
	(s1.*fp)();
	(s2.*fp)();
	// ps1->*fp(); // error: must use '.*' or '->*' to call pointer-to-member function in 'fp (...)'
	(ps1->*fp)(); 
	
	// (int)高于.*和->*:先结合(int)
	cout << "-----------------6------------------" << endl;
	student2 *ssp = &sss;   // jason
	void (student2::*fp2)();
	fp2 = student2::printinfo;
	(ss.*fp2)();
	((student)ss.*fp)();  // 先将ss强转为student,然后调用student::printinfo(),注意是.*fp而不是.*fp2
	((student*)ssp->*fp)();  // 先将ssp强转为student*,然后调用student::printinfo(),注意是.*fp而不是.*fp2

	// *高于.*和->*:先结合*
	cout << "-----------------7------------------" << endl;
	(*ssp.*fp2)();   // 先*ssp,再.*fp2
	student2 **sspp = &ssp;
	(*sspp->*fp2)(); // 先*sspp,再->*fp2
	
	delete ps1;
	return 0;
}

输出:

-----------------1------------------
i am a student. my name is bob. my id is 101
i am a student. my name is jack. my id is 102
i am a student. my name is eric. my id is 103
-----------------2------------------
i am a student. my name is eric. my id is 103
-----------------3------------------
i am a student. my name is eric. my id is 103
i am a student. my name is eric. my id is 103
-----------------4------------------
i am student2!!!
i am a student. my name is alice. my id is 999
i am a student. my name is jason. my id is 998
-----------------5------------------
i am a student. my name is bob. my id is 101
i am a student. my name is jack. my id is 102
i am a student. my name is eric. my id is 103
-----------------6------------------
i am a super student!!!
i am a student. my name is alice. my id is 999
i am a student. my name is jason. my id is 998
-----------------7------------------
i am a super student!!!
i am a super student!!!

到此这篇关于探究c++中指针与数组运算符优先级的文章就介绍到这了,更多相关c++指针和数组运算符优先级内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com