STL container assignment and const pointers

前端 未结 8 1746
时光取名叫无心
时光取名叫无心 2020-12-29 11:52

This compiles:

int* p1;
const int* p2;
p2 = p1;

This does not:

vector v1;
vector v2;
v2 = v1;         


        
相关标签:
8条回答
  • 2020-12-29 12:38

    Conversion from int* to const int* is built into the language, but vectors of these have no automatic conversion from one to the other.

    0 讨论(0)
  • 2020-12-29 12:42

    The issue is not the pointers, but the types of the two vectors. There are no standard conversions between templated types like those of v1 and v2 in your example.

    This is perhaps easier to see in the following code:

    #include <vector>
    using namespace std;
    
    int main() {
        vector <char> cv;
        vector <int> iv;
        cv = iv;    // error
    }
    
    0 讨论(0)
提交回复
热议问题