C++ 关于函数返回数组引用、左值的问题
查看原帖
C++ 关于函数返回数组引用、左值的问题
482114
DIaacKr楼主2021/2/8 11:44

问题主要出现在ans2,在使用ans2[i]试图与'0'比较是否相等时。编译器报错,提示“表达式必须为可修改的左值”。(用的IDE : visual studio 2019) 按本人程序设计的想法,ans2为函数返回的数组的引用,此处ans2[i]则访问引用中绑定的对象的值。我感觉是关于引用方面的知识的不够了解导致的错误,但不知道错在哪,望指点一二。 另外我试了了不用ans2,直接用ans1,但依旧是提示“表达式必须为可修改的左值”,QAQ... 代码较蹩脚,希望得到指点,感激不尽orz

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

//auto add(const char(&a)[500], const char(&b)[500], char(&re)[501]) -> char(&)[501]
char(&add(const char(&a)[500], const char(&b)[500], char(&re)[501]))[501]
{
	size_t len1(strlen(a)),len2(strlen(b));
	char jw = 0;
	for (size_t i = 0; i <= len1; ++i)
	{
		re[i] = a[i] + b[i] - 48 + jw;
		if (re[i] > 57)
		{
			re[i] -= 9;
			jw = 1;
		}
		else jw = 0;
	}
	for (size_t i = len1 + 1; i <= len2; ++i)
	{
		re[i] = b[i] + jw;
		if (re[i] > 57)
		{
			re[i] -= 9;
			jw = 1;
		}
	}
	return re;
}

int main()
{
	char str1[500]({ 0 }), str2[500]({ 0 }), ans1[501]({ 0 });
	while (cin >> str1 >> str2)
	{
		if (strlen(str2) > strlen(str1))
		{
			char(&ans2)[501](add(str1, str2, ans1));
			int flag = 0;
			for (size_t i = 500; i >= 0; ++i)
			{
				if (ans2[i]=='0' && flag = 0);
				else
				{
					cout << ans2[i];
					flag = 1;
				}
			}
			cout << endl;
		}
		else
		{
			char(&ans2)[501](add(str2, str1, ans1));
			int flag = 0;
			for (size_t i = 500; i >= 0; ++i)
			{
				if (ans2[i] == '0' && flag = 0);
				else
				{
					cout << ans2[i];
					flag = 1;
				}
			}
			cout << endl;
		}
	}

	return 0;
}
2021/2/8 11:44
加载中...