簡體   English   中英

std :: vector :: operator的模棱兩可的重載[]

[英]Ambiguous overload of std::vector::operator[]

我有一個簡單的包裝程序來包裝以C終止的字符串,該字符串本質上是std :: vector <char>的子類。 (是的,我知道std :: string,但是我的包裝器更容易與期望char *的C函數配合使用。而且,在C ++ 03中,std :: string不能保證是連續的)

這是代碼:

#include <cstdio>
#include <vector>

typedef std::vector<char> vector_char;
class c_string : public vector_char
{
    public:
    c_string(size_t size) : vector_char(size+1) {}

    c_string(const char* str)
    {
        if(!str) return;
        const char* iter = str;
        do
            this->push_back(*iter);
        while(*iter++);
    }

    c_string() {}

    //c_string(std::nullptr_t) {}

    char* data()
    {
        if(this->size())
            return &((*this)[0]); //line 26
        else
            return 0; 
    }

    const char* data() const { return this->data(); }

    operator char*() { return this->data(); }
    operator const char*() const { return this->data(); }

};

int main()
{
    c_string first("Hello world");
    c_string second(1024);

    printf("%s",first.data());
    printf("%c\n",first[0]);
    snprintf(second, second.size(), "%d %d %d", 5353, 22, 777);
    printf(second);
}

MinGW抱怨:

D:\prog\PROJEKTYCPP\hehe_testc_cpp.cpp: In member function 'char* c_string::data()':

D:\prog\PROJEKTYCPP\hehe_testc_cpp.cpp:26:22: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]

In file included from d:\prog\mingw\bin\../lib/gcc/mingw32/4.7.0/include/c++/vector:65:0,
                 from D:\prog\PROJEKTYCPP\hehe_testc_cpp.cpp:2:
d:\prog\mingw\bin\../lib/gcc/mingw32/4.7.0/include/c++/bits/stl_vector.h:768:7:note: candidate 1: std::vector<_Tp, _Alloc>::reference std::vector<_Tp, _Alloc>::operator[]:(std::vector<_Tp, _Alloc>::size_type) [with _Tp = char; _Alloc = std:
:allocator<char>; std::vector<_Tp, _Alloc>::reference = char&; std::vector<_Tp,_Alloc>::size_type = unsigned int]


D:\prog\PROJEKTYCPP\hehe_testc_cpp.cpp:26:22: note: candidate 2: operator[](char
*, int) <built-in>

如何強制調用正確的重載? 這個問題可以默默地傷害我嗎?

通過使用運算符char *您提供了兩種執行operator[] 第一個是std::vector::operator[]直接應用; 二是要轉變thischar*和應用[]這一點。 在這種情況下,它們都導致相同的結果,但是編譯器無法知道。

通過明確指定您想要的解決它。

        return &(operator[](0)); //line 26

要么

        return &((char*)(*this)[0]); //line 26

要刪除第一個警告,可以執行以下操作:

char* data()
{
    if(this->size())
        return &vector_char::operator[](0);
    else
        return 0;
}

要刪除所有警告,請刪除operator char*()operator const char*()成員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM