重载+添加两个指针 [英] Overloading + to add two pointers
问题描述
我有一个String类,我想重载+添加两个String *指针. 像这样的东西行不通:
I have a String class and I want to overload + to add two String* pointers. something like this doesn't work:
String* operator+(String* s1, String* s2);
有什么方法可以避免通过引用传递. 考虑以下示例:
Is there any way to avoid passing by reference. Consider this example:
String* s1 = new String("Hello");
String* s2 = new String("World");
String* s3 = s1 + s2;
我需要这种补充才能工作.请提出建议.
I need this kind of addition to work. Please suggest.
推荐答案
您不能.您不能重载内置类型的运算符.无论如何,为什么要使用指针呢?尽可能避免动态分配!
You can't. You cannot overload operators for built-in types. In any case, why use pointers at all? Avoid dynamic allocation as much as possible!
String s1("Hello");
String s2("World");
String s3 = s1 + s2;
那好多了,而且不会泄漏.现在您可以重载:
That's much better, and doesn't leak. Now you can overload:
String operator+(const String& s1, const String& s2);
你的愿望.当然,这是浪费时间,因为存在std::string
. :)
how you desire. This is, of course, a waste of time because std::string
exists. :)
这篇关于重载+添加两个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!