gpt4 book ai didi

c++ - 类设计建议 - C++

转载 作者:行者123 更新时间:2023-11-27 23:35:34 26 4
gpt4 key购买 nike

背景

我正在开发一个语音转换器程序,可以将英文文本转换为等效的区域语言文本。区域性语言的字符比英文字母多,区域性语言字体几乎使用字体中的所有位置 (1-255)。

我的程序支持不同的字体,我已经创建了一个字体类,它有方法可以访问字符。这个类将有 255 个方法,每个方法代表每个字符。所有这些都标记为虚拟,以便新字体可以覆盖必要的字符方法。

这个字体类中的方法很简单。所有方法都是单行的。例子是

string StandardFont::consonant1(){
return "a";
}

string StandardFont::consonant2(){
return "b";
}

..

问题

  1. 一个类中有 255 个虚函数会不会产生任何性能问题?我知道 vtable 的东西,但我不确定它在这种情况下有多大影响。
  2. 谁能为这个类(class)推荐一个替代设计?主要设计目标是允许派生类覆盖必要的方法。我考虑过将字符添加到容器中,例如 mapvector 并提供获取字符的方法。但是由于我将有 255 个项目并且这个类被频繁使用,我认为每次我都必须循环容器来获取角色,这又是一个问题。

有什么想法吗?

最佳答案

我建议您使用非 ASCII(区域)字符的标准编码。

标准编码称为“unicode”,例如http://www.joelonsoftware.com/articles/Unicode.html

无论如何:回答你的问题......

Will 255 virtual functions in a single class make any performance issues?

一句话:不会,不会。

But since I will have 255 items and this class is used frequently, I think each time I have to loop the container to get the character, which is again an issue.

对于长度为 256 的 vector 或定长数组,您不需要循环...而是可以直接索引,例如:

const char* translations[256] = {
"a",
"bee",
"c!",
...etc...
};

const char* translate(char c)
{
//use the character as an index into the array
int index = c;
//use the translation array (using indexing, not looping)
const char* result = translations[index];
return result;
}

关于c++ - 类设计建议 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/486252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com