15种 C++ 常见报错原因分析

本文整合了部分 C/C++ 常见的报错原因,可根据自己的情况,使用目录跳转。

1 重定义变量

#include
using namespace std;
 
int main()
{
	int a;
	cin>>a;
	int a;
	cout< 
 

Error:redefinition of 'a'

改为:

#include
using namespace std;
 
int main()
{
	int a;
	cin>>a;
	cout< 
 

2  缺少分号

#include
using namespace std;
 
int main()
{
	int a;
	cout< 
 

Error:expected ';' after expression

改为:

#include
using namespace std;
 
int main()
{
	int a;
	cout< 
 

3 数组维数错误

#include
using namespace std;
 
int main()
{
	int a[101][101];
	a[0]=1;
	cout< 
 

Error:array type 'int [101]' is not assignable

改为:

#include
using namespace std;
 
int main()
{
	int a[101];
	a[0]=1;
	cout< 
 

4  关于 if 与 else

#include
using namespace std;
 
int main()
{
	int a;
	cin>>a;
	if (a==1;) a=2;
}

Error:expected expression

Warning: equality comparison result unused [-Wunused-comparison]

if 判断里不能有分号!

改为:

#include
using namespace std;
 
int main()
{
	int a;
	cin>>a;
	if (a==1) a=2;
}

5  关于 if 与 else

#include
using namespace std;
 
int main()
{
	int a;
	cin>>a;
	if (a=1) a=2;
}

这个是把等号写成了赋值号

 Warning: using the result of an assignment as a condition without parentheses [-Wparentheses]

这个超级坑爹,因为不少编译器遇到这种问题有的还不报错,只是有Warning,而且看半天才能看出来

应改为:

#include
using namespace std;
 
int main()
{
	int a;
	cin>>a;
	if (a==1) a=2;
}

6  括号匹配错误

#include
using namespace std;
 
int main()
{
	int a[10];
	a[1=(a[1+1)*1);
	}
 
}

Error: expected ']'

Error: expected ']'

Error: extraneous closing brace ('}')

应改为:

#include 
using namespace std;
char c[101];
 
int main() 
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin>>c+1;
	return 0;
}

===========Upd: 22-05-19============

7  关于字符串的输入错误 (*)

#include using namespace std;char c[101];int main() {ios::sync_with_stdio(0);cin.tie(0);cin>>c+1;return 0;}

(MacOS⬇️⬇️⬇️)

Error:  invalid operands to binary expression ('std::istream' (aka 'basic_istream') and 'char *')
        cin>>c+1;
        ~~~^ ~~~

Warning: operator '>>' has lower precedence than '+'; '+' will be evaluated first [-Wshift-op-parentheses]
        cin>>c+1;
           ~~~^~

和一堆 note:

Note: candidate function template not viable: no known conversion from 'std::istream' (aka 'basic_istream') to 'std::byte' for 1st argument
  operator>> (byte  __lhs, _Integer __shift) noexcept
  ^

(这句话至少出现了50次)

那么为什么打*呢?

因为 Linux 系统编译通过!

Windows 尚未测试,有兴趣的小伙伴可以自测一下然后私信,欢迎私信~~~。

(这个问题源于我自己做题时,我看标准代码,不知为什么就是编译不对,结果提交以后就AC了?!)

8  写错函数 / 变量名

这个情况下,有时候编译器可能会猜测你要写的名字,比如:

#include 
using namespace std;
 
int main() 
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	int a=1,b=2;
	mam(a,b);
	return 0;
}

Error: use of undeclared identifier 'mam'; did you mean 'max'?

如果编译器没有类似提示,就仔细想想应该是什么吧。

到此这篇关于15种 C++ 常见报错的文章就介绍到这了,更多相关C++ 常见报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(15种 C++ 常见报错原因分析)