c++ - 指针和引用可以重载吗?
天蓬老师
天蓬老师 2017-04-17 11:41:07
0
1
545

比如是否允许一个函数传入指针,或者传入引用。

swap(T* a, T* b) {}

同时允许

swap(T& a, T& b) {}

C++是否允许这样的重载?
我试验了一下,编译器调用引用方式函数的时候会报错。
如果语言允许,应该怎么声明?

谢谢。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
左手右手慢动作

Such overloading should be allowed. The following is the test code (it can also work normally before adding template)

#include <cstdio>

template<typename T> void swap(T *a, T *b)
{ T t = *a; *a = *b; *b = t; }

template<typename T> void swap(T &a, T &b)
{ T t = a; a = b; b = t; }

int main()
{
    int x = 3, y = 6;
    printf("%d %d\n", x, y);
    swap<int>(&x, &y);
    printf("%d %d\n", x, y);
    swap<int>(x, y);
    printf("%d %d\n", x, y);
    return 0;
}

Is this what the question means? Also, "the compiler will report an error when calling a reference function" does this mean that the compiler reports an error? Can you give an error message?
Thank you


EDIT:
I see the following content in your error message:

..../type_traits:3201:1: note: candidate function [with _Tp = int]

The function name should be duplicated with the swap function definition in the type_traits file (maybe the compiler automatically includes it), resulting in an error. You can try changing the name of the swap function in the test code to resolve the conflict.

PS The compilation command I used: g++ -Wall -o test test.cpp

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template