c++错误集合

来源:互联网 发布:tcl董事长广告 知乎 编辑:程序博客网 时间:2024/06/16 21:25

1. 错误:expected unqualified-id before ‘using’ 

其实就是类声明后面没有加分号导致的。
类声明的时候没有加分号,还可能导致一个错误
错误:一个声明指定了多个类型
解决办法:分别检查包含进来的文件,类声明,结构体声明后面有没有加分号。

2. 重载运算符<<用到的 std中的变量名。

using std::ostream;

3. C++容器迭代器即其引用

#include <vector>
using std::vector;
int main()
{
    vector<int> ivec(10, 10);
   vector<int>::iterator it1 = ivec.begin();                     //都知道,正确
  //vector<int>::iterator &it2 = ivec.begin();                 //编译出错
  const vector<int>::iterator &it3 = ++ ivec.begin();     //正确
  system("pause");
  return 0;
}
为什么会这样呢?
很明显ivec.begin()返回的是一个右值,是一个vector<int>::iterator类型的临时对象。
而引用只是它所绑定的对象的别名,对象不存在了,引用当然就没必要存在啦!
也就是说引用不能用临时变量初始化!

4. 编译运行以下代码出错:ISO C++ forbids cast to non-reference type used as lvalue
(禁止转换为非引用类型的左值使用)


5. G++ 编译错误:multiple types in one declaration 如何解决?

解决方法:查看你写的每个类,是否在“}”后加上了“;”。


6. error: variable ‘std::istringstream stream’ has initializer but incomplete type

解决方法:在头文件中添加#include<sstream>

7. invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type ‘std::string’

#include<iostream>
#include<string>
using std::cout;
using std::string;
using std::endl;
void PrintStr(std::string& str);
int main()
{
    PrintStr(string("HelloWorld!"));   //string("HelloWorld!")  为一个临时变量
    return 0;
}
void PrintStr(std::string& str)
{
    cout<< str << endl;
}
说明:临时变量是转瞬即逝的,在上面的代码中,用str引用临时变量的时候临时变量已经不存在了。
解决方案:void PrintStr(std::string& str);改为void PrintStr(const std::string& str);
const 引用可以初始化为不同类型的对象或者初始化为右值。例如:
double dval = 1.131;
const int &ri = dval;

const int &r = 30;

8.

C++中 runtime_error的问题

试试#include<stdexcept>这个。<exception>中定义了exception这个处理异常的基类,而<stdexcept>中是已经实现好的异常处理类,从exception这个类继承过来的。所以如果只是用out_of_range, runtime_error这些,包含<stdexcept>就可以了。而入股您想自己实现一个异常类,则包含<exception>,从exception类继承过来加以实现。