有没有办法在C ++中扩展数据类型,就像在JavaScript中一样?
我想这有点像这样:
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());
这应该以某种方式打印。
答案 0 :(得分:2)
在C ++中没有办法实现这一点。在我看来,最接近这一点的是创建一个类似内置类型的类,但会提供额外的功能。永远不可能使它们100%像内置类型一样工作,尽管“代理”类型并不总是理想的。
答案 1 :(得分:1)
最接近的是使用运算符重载,例如
#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
初始化它的构造函数。
答案 2 :(得分:0)
不,JavaScript基于对象的原型。此概念不适用于C++。它们是如此不同的语言,我甚至无法向您展示您的问题的反例。