我将函数fn
重载为fn(int,char)
& fn(int&,char&)
如下所示:
#include <iostream>
using namespace std;
void fn(int a, char c);
void fn(int& a, char& c);
int main()
{
int a=10;
char c= 'c';
cout << "Inside main()" << endl;
cout << hex << "&a : " << &a << endl;
cout << hex << "&c : " << (int *)&c << endl;
static_cast<void(*) (int&, char&)> (fn)(a, c);
return 0;
}
void fn(int a, char c)
{
int tempInt;
char tempChar;
cout << "\n\nInside Call By Value Function " << endl;
cout << hex << "&a : " << &a << endl;
cout << hex << "&c : " << (int *)&c << endl;
cout << hex << "&tempInt : " << &tempInt << endl;
cout << hex << "&tempChar : " << (int *)&tempChar << endl;
}
void fn(int& a, char& c)
{
cout << "\n\nInside Call By Reference Function " << endl;
cout << hex << "*a : " << &a << endl;
cout << hex << "*c : " << (int*) &c << endl;
}
致电fn(int,char)
或fn(int&,char&)
的决议是通过施法static_cast<void(*) (int&, char&)> (fn)(a, c);
它提供输出:
$ ./Overloading
Inside main()
&a : 0x22ac5c
&c : 0x22ac5b
Inside Call By Reference Function
*a : 0x22ac5c
*c : 0x22ac5b
现在当我把它放在如下的课程中时:
#include <iostream>
using namespace std;
class Test{
public:
void fn(int a, char c);
void fn(int& a, char& c);
};
int main()
{
int a=10;
char c= 'c';
Test T();
cout << "Inside main()" << endl;
cout << hex << "&a : " << &a << endl;
cout << hex << "&c : " << (int *)&c << endl;
static_cast<void(*) (int&, char&)> (T.fn)(a, c);
return 0;
}
void Test::fn(int a, char c)
{
int tempInt;
char tempChar;
cout << "\n\nInside Call By Value Function " << endl;
cout << hex << "&a : " << &a << endl;
cout << hex << "&c : " << (int *)&c << endl;
cout << hex << "&tempInt : " << &tempInt << endl;
cout << hex << "&tempChar : " << (int *)&tempChar << endl;
}
void Test::fn(int& a, char& c)
{
cout << "\n\nInside Call By Reference Function " << endl;
cout << hex << "*a : " << &a << endl;
cout << hex << "*c : " << (int*) &c << endl;
}
我得到以下错误:
$ g++ -Wall Overloading.cpp -o Overloading
Overloading.cpp: In function ‘int main()’:
Overloading.cpp:23:42: error: request for member ‘fn’ in ‘T’, which is of non-class type ‘Test()’
我该如何解决这个问题?
如何正确拨打T's fn(int&,char&)
我想在我的代码中表达式static_cast<void(*) (int&, char&)> (T.fn)(a, c);
是不正确的。
请帮忙。
由于
修改
我的错误
将Test T()
修改为Test T;
给出错误
$ g++ -Wall Overloading.cpp -o Overloading
Overloading.cpp: In function ‘int main()’:
Overloading.cpp:23:44: error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘void (*)(int&, char&)’
答案 0 :(得分:2)
首先:T
不是变量,T
是函数,它返回Test
并且什么都不收。
第二:函数指针不是成员函数指针。您应该使用此语法
typedef void (Test::*function)(int&, char&);
function f = &Test::fn;
(T.*f)(a, c);
答案 1 :(得分:0)
请参阅error: request for member '..' in '..' which is of non-class type:问题出在Test T();
,请尝试省略括号。
答案 2 :(得分:0)
当您执行Test T();
时,您说T
是一个返回类型为Test
的函数。但是你的代码中不存在这样的东西。
解决方案是:
Test T;