• 【小白C++学习之路】C++常见错误总结


    1、临时变量的非const引用


     

    class Solution {
    public:
        void __dfs(vector<string> &paths, string &path, int loc, int n, int left, int right)
            {
                if (loc == 2*n){
                    paths.push_back(path);
                    return;
                }
                
                if (left < n){
                    __dfs(paths, path+"(", loc+1, n, left+1, right);
                    //path.pop_back();
                }
                if (right < left){
                    __dfs(paths, path+")", loc+1, n, left, right+1);
                    //path.pop_back();
                }
                
                
            }
        vector<string> generateParenthesis(int n) {
            // 递归法来做
            vector<string> paths;
            string s;
            __dfs(paths, s, 0, n, 0, 0);
            return paths;        
        }
        
        
    };

     

    编译报错:Line 11: Char 34: error: cannot bind non-const lvalue reference of type 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string<char>&'} to an rvalue of type 'std::__cxx11::basic_string<char>'

     

    这个错误是C++编译器的一个关于语义的限制。

    如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,所以,一般说来,修改一个临时变量是毫无意义的,据此,c++编译器加入了临时变量不能作为非const引用的这个语义限制。

    2、string对象的索引返回是char型


    string s = "hello";
    
    // s[1]返回类型是char
  • 相关阅读:
    kubectl 命令详解
    codeforce344 C report
    poj3041 建图+最小顶点覆盖(最大匹配数)
    poj1637 混合欧拉回路的判定
    poj1149 最大流好题 难在建图 好题
    targan 算法模板
    poj2186 强连通分量 targan算法的应用
    poj2723 2分 + 2-sat
    poj3061 尺取法
    poj3207 2-sat基础题
  • 原文地址:https://www.cnblogs.com/ACStrive/p/11573870.html
Copyright © 2020-2023  润新知