我有一个简单的 C 空终止字符串包装器,它本质上是 std::vector< char > 的子类。(是的,我知道 std::string,但我的包装器更容易与期望 char* 的 C 函数合作。此外,std::string 不能保证在 C++03 中是连续的)
这是代码:
#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>
如何强制调用正确的重载?这个问题能默默地伤害我吗?