C++-扩展数据类型
C++ - extending a data type
有没有一种方法可以像在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++。它们是如此不同的语言,我甚至不能给你举一个反例来回答你的问题。
相关文章:
- 防止主数据类型C++的隐式转换
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在C++中打印指向不同基元数据类型的指针的内存地址
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何计算数据类型的范围,例如int
- C++中数据类型修饰符的顺序
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 特定数据类型的模板类
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何获取C++字符数据类型的地址
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 构造智能点数据类型以及普通数据类型的通用方法
- 如何使映射键具有两种不同的数据类型?
- c++hdf5:如何设计易于扩展到新的复合数据类型的程序
- C++-扩展数据类型
- 其他类数据类型的扩展boost::lexical_cast