首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

G++上的函数指针与vc不一样

2013-03-20 
G++下的函数指针与vc不一样直接上代码:#include iostreamusing namespace stdint mymax(int x, int y){

G++下的函数指针与vc不一样
直接上代码:


#include <iostream>

using namespace std;

int mymax(int x, int y)
{
    return x>y?x:y;
}

int mymin(int x, int y)
{
    return x<y?x:y;
}
int main()
{
    typedef int (* fun_ptr) (int,int);
    fun_ptr fptr;
    fptr = mymax;
    int t,s;
    t = fptr(5,3);  ////qa
    s = (*fptr)(1,2); ////qb
    cout<<t+s<<endl;
    cout<<fptr<<endl; ///qc
    cout<<mymin<<endl;///qd
    return 0;
}


问题是,在g++下,运行结果qc和qd一直都是输出1,
但是在vc6.0下却能够正确的输出地址,这是为什么呢?

还有一个问题,在只用函数指针调用函数时,qa和qb两种型式有没有区别?
函数指针 g++ vc++6.0
[解决办法]
直接输出指针不合理吧,至少要类型转换一下再输出啊
cout<<reinterpret_cast<int>(fptr)<<endl; ///qc
    cout<<reinterpret_cast<int>(mymin)<<endl;///qd


qa和qb两种使用方法都是正确的,没什么区别
[解决办法]
MS和g++用的STL不一样,在ostream的<<重载上选择了不同的重载方式。。

g++应该是从指针到bool
MS 应该是从指针到void*
[解决办法]
VS是错误的,G++是正确的。


There are no overload for pointers to volatile or function pointers (other than the ones with signatures accepted by the 9) overload). Attempting to output such objects invokes implicit conversion to bool, and, for any non-null pointer value, the value 1 is printed (unless boolalpha was set). 

http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt

[解决办法]
引用:
VS是错误的,G++是正确的。


There are no overload for pointers to volatile or function pointers (other than the ones with signatures accepted by the 9) overload). Attempting to output such objec……


正解。因为函数指针是不允许转换为void *的。

热点排行