为 ISO 8859-1 实施basic_string<无符号字符>

Implementing basic_string<unsigned char> for ISO 8859-1

本文关键字:lt 字符 gt 无符号 string 8859-1 ISO 实施 basic      更新时间:2023-10-16

背景:

我是一名C程序员,我刚刚决定玩C++。

目标:

创建一个类,使用std::basic_string将ISO 8859-1字符作为字符串读取。我知道我可以在std::string中使用映射函数,但出于学习的原因,我想尝试这种方式。

问题:

我创建了一个从char_traits扩展的类和一个实现basic_string的类。现在我正在尝试创建构造函数。构造函数应该接受const char指针并为其分配空间

基于此,此构造函数已经存在:

basic_string (const charT* s, const allocator_type& alloc = allocator_type());

它被定义为:

来自c字符串

Copies the null-terminated character sequence (C-string) pointed by s.
The length is determined by calling traits_type::length(s)."

所以我假设我可以重用那个构造函数,传递正确的参数(在这种情况下,是无符号的char而不是char(,但要么我不知道如何正确使用默认参数,要么构造函数不存在。

我不确定这是否是正确的方法,所以欢迎任何关于如何做到这一点的提示。

错误:

test.cpp: In constructor ‘ISO_8859_1_String::ISO_8859_1_String(const char*)’:
test.cpp:18:72: error: no matching function for call to ‘ISO_8859_1_String::ISO_8859_1_String(const unsigned char*, NULL)’
test.cpp:18:72: note: candidates are:
test.cpp:16:5: note: ISO_8859_1_String::ISO_8859_1_String(const char*)
test.cpp:16:5: note:   candidate expects 1 argument, 2 provided
test.cpp:14:7: note: ISO_8859_1_String::ISO_8859_1_String(const ISO_8859_1_String&)
test.cpp:14:7: note:   candidate expects 1 argument, 2 provided

代码:

#include <iostream>
using namespace std;
class ISO_8859_1_Char_Traits : public char_traits<unsigned char>{
  public: 
    // Simple length implementation
    static size_t length (const unsigned char* s){
      size_t i = 0;
      while (s[i++] != 0x00){};
      return i;
    }
};
class ISO_8859_1_String : public basic_string<unsigned char, ISO_8859_1_Char_Traits, allocator<unsigned char> >{
  public:
    ISO_8859_1_String(const char* s){
      ISO_8859_1_String(reinterpret_cast<const unsigned char*>(s), NULL);
   }
};
int main(){
  ISO_8859_1_String* test = new ISO_8859_1_String("test");
  
  return 1;
}

在此:

class ISO_8859_1_String : public basic_string<unsigned char, ISO_8859_1_Char_Traits, allocator<unsigned char> >{
  public:
    ISO_8859_1_String(const char* s){
      ISO_8859_1_String(reinterpret_cast<const unsigned char*>(s), NULL);
   }
};

要么是我的眼睛在欺骗我,要么是你用错误数量的参数调用构造函数(事实证明,在构造函数本身(。此外,即使你传递了正确数量的参数,你也会无限递归。

编辑:另外,第一个参数的类型无论如何都不匹配。

第二版:好吧,我想我知道你想做什么了。你想把参数传递给基类的构造函数。为此,您需要不同的语法:

    ISO_8859_1_String(const char* s)
     : basic_string<unsigned char, ISO_8859_1_Char_Traits, allocator<unsigned char> >(reinterpret_cast<const unsigned char*>(s), NULL) {
   }

此外,我会使用一些类型别名或typedef来提高可读性。

附录:基类ctor参数必须通过初始化列表传递,而不是在派生类ctor:的主体中传递

class A {
    A() {}
    A(int) {}
};
class B1 : public A{
    // This means: Call the base class ctor with a 1.
    B1() : A(1) {]
    // This means: Call the base class ctor with no arguments.  Then create a
    // temporary A object, passing 1 to the ctor, and then throw it away.
    // B1() { A(1); }
};