Contents

C++:错误收集

本文采用知识共享署名 4.0 国际许可协议进行许可,转载时请注明原文链接,图片在使用时请保留全部内容,可适当缩放并在引用处附上图片所在的文章链接。

basic_string::_M_construct

1
2
3
terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Aborted (core dumped)

string构造不能传入空指针xxx,即在xxx为空时会报上面错误,保证func返回不为空即可。

多态失效问题的

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class vehicle{
    public:
        void run(){
            std::cout<<"from vehicle:run"<<std::endl;
        }
};

class car:public vehicle{
    public:
        void run(){
            std::cout<<"from car:public vehicle:run"<<std::endl;
        }
};

void call_fun(vehicle *pvehicle){
    pvehicle->run();
}

int main(){
    vehicle *_pvehicle = new vehicle();
    car *_pcar = new car();
    call_fun(_pvehicle);
    call_fun(_pcar);
    delete _pvehicle;
    delete _pcar;
    return 0;
}

输出

1
2
from vehicle:run
from vehicle:run

在C++中,如果在基类和派生类中对同一个函数都进行了定义时,通过基类和派生类指针对象调用成员函数时具体是执行哪一个类实例的成员函数是根据接口函数的参数类型而定,而不是实际的类实例指针对象

C++ const函数返回值必须为const引用

参考: C++ const函数返回值必须为const引用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>

class MyString
 {
 public:
     MyString(std::string T):text(T){}
     const char& operator[](std::size_t position) const // operator[] for const 对象
     { return text[position]; }

     char& operator[](std::size_t position)  // operator[] for non-const 对象
     { return text[position]; }
 private:
    std::string text;
};

int main(){
    MyString ms("coding"); // non-const 对象
    MyString test("testing");
    std::cout << ms[0]<< std::endl;   // 调用 non-const MyString::operator[]
    ms[0] = 'x';          // 没问题,写一个 non-const  MyString

    const MyString cms("coding"); // const 对象
    std::cout << cms[0]<<std::endl;   // 调用 const MyString::operator[]
    //cms[0] = 'x';          // 错误! 写一个 const  MyString
}