您的位置:首页 > 编程语言 > C语言/C++

C++ 常见编译错误

2013-07-20 17:30 274 查看
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: