【问题标题】:Two functions having same body different name具有相同主体不同名称的两个函数
【发布时间】:2018-06-14 03:37:15
【问题描述】:

是否可以有两个函数名称不同但功能相同的函数共享函数体?我们该怎么做呢?

template<typename _T>
class array {
public:
    _T operator+(_T concatinate_operand); // concatinate to the array
    _T append(_T concatinate_operand);
};

【问题讨论】:

  • 你可以只打一个电话。
  • 但是您需要不同的+ 运算符重载语义。 IE。类似array&amp; operator+(const array&amp; rhs) { append(rhs.data_,rsh.length_); return *this; };
  • 完全和完全无关:任何时候在大写字母前加下划线时都表现出一点恐惧。为什么,请阅读What are the rules about using an underscore in a C++ identifier?

标签: c++ function


【解决方案1】:

是的,这很容易实现。您只需调用该函数,然后从另一个函数中执行实际实现。那看起来像

template<typename _T>
class array {
public:
    _T operator+(_T concatinate_operand) { return append(concatinate_operand); } // concatinate to the array
    _T append(_T concatinate_operand) { /*actual logic here*/ }
};

请注意,如果T 很大,则按值传递它并获取副本会损害性能。如果您使用类似的参考文献

template<typename _T>
class array {
public:
    _T& operator+(const _T& concatinate_operand) { return append(concatinate_operand); } // concatinate to the array
    _T& append(const _T& concatinate_operand) { /*actual logic here*/ }
};

您将避免不必要的复制。

【讨论】:

  • operator+ 返回T&amp; 会很奇怪。或者奇怪的是 operator+append 应该做同样的事情。
  • _T&amp; operator+(const _T&amp; concatinate_operand) 实际上是个坏主意 :) char * foo = nullptr; if(some) { array&lt;char&gt; arr("abcd",5); foo = arr + "12345"; } delete [] foo;
  • @VictorGubin 该代码应该是/做什么?它无法编译,而且似乎在尝试做一些可怕的事情。
  • @VictorGubin 很抱歉,我不明白您要表达的意思。
  • @VictorGubin 为什么?那不是OP所拥有的。看起来想要使用+append 在数组末尾添加一个元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 2014-11-12
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
相关资源
最近更新 更多