C++-扩展数据类型

C++ - extending a data type

本文关键字:数据类型 扩展 C++-      更新时间:2023-10-16

有没有一种方法可以像在JavaScript中那样在C++中扩展数据类型?

我想这是这样的:

char data[]="hello there";
char& capitalize(char&)
{
    //Capitalize the first letter. I know that there
    //is another way such as a for loop and subtract
    //whatever to change the keycode but I specifically 
    //don't want to do it that way. I want there
    //to be a method like appearance.
}
printf("%s", data.capitalize());

这应该以某种方式打印出来。

在C++中没有办法做到这一点。在我看来,最接近这一点的方法是创建一个类,它的行为与内置类型类似,但会提供额外的功能。尽管"代理"类型并不总是理想的,但永远不可能让它们像内置类型那样100%工作。

最接近的方法是使用运算符重载,例如

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
std::string operator!(const std::string& in) {
  std::string out = in;
  std::transform(out.begin(), out.end(), out.begin(), (int (*)(int)) std::toupper);
  return out;
}
int main() {
  std::string str = "hello";
  std::cout << !str << std::endl;
  return 0;
}

替代方法包括创建一个重载operator std::string的类,以及使用std::string初始化它的构造函数。

不,JavaScript是基于对象原型的。这个概念不适用于C++。它们是如此不同的语言,我甚至不能给你举一个反例来回答你的问题。