我重载了一个函数,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&)’