繁体   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