免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 2849 | 回复: 16
打印 上一主题 下一主题

[C++] c++函数指针的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-11-13 23:38 |只看该作者 |倒序浏览
#include<iostream>
//#include<vector>
#include<cmath>
using namespace std;
class A{
private:
        typedef void (*p)(int i);
        p pp;
public:
        void print(int i){
                cout<<i<<endl;
        }
        A()
        {
                this->pp=print;
        }
};
int main()
{
}
这个程序在VC6.0下有一个错误。麻烦知道不啬告诉我,先谢谢了

论坛徽章:
0
2 [报告]
发表于 2006-11-14 10:36 |只看该作者
类型不匹配。
void (*p)(int)
void (A::*p)(int)
注意类成员函数的“类属属性”。

论坛徽章:
0
3 [报告]
发表于 2006-11-14 14:09 |只看该作者
原帖由 namtso 于 2006-11-14 10:36 发表
类型不匹配。
void (*p)(int)
void (A::*p)(int)
注意类成员函数的“类属属性”。



可是我改成下面这样怎么编译有错误呢?
#include<iostream>
//#include<vector>
#include<cmath>
using namespace std;
class A{
private:
        typedef void (A::*p)(int i);
        p pp;
public:
        void print(int i){
                cout<<i<<endl;
        }
        A()
        {

        }
                void test()
                {
                        this->pp=print;       
                        pp(4);
                }
};
int main()
{
        return 0;
}

编译提示:
Compiling...
test.cpp
C:\Documents and Settings\administrator.NEUSOFT-CUICP\桌面\test.cpp(20) : error C2064: term does not evaluate to a function
Error executing cl.exe.

test.exe - 1 error(s), 0 warning(s)

谢谢!!

论坛徽章:
0
4 [报告]
发表于 2006-11-14 15:06 |只看该作者
类里的函数指针,
改了一下 LZ看看行不行

#include<iostream>
//#include<vector>
#include<cmath>
using namespace std;
class A{
private:
        typedef void (A::*p)(int i);
        p pp;
public:
        void print(int i){
                cout<<i<<endl;
        }
        A()
        {
                this->pp=&A::print;
        }
};
int main()
{
}

[ 本帖最后由 la.lune 于 2006-11-14 15:23 编辑 ]

论坛徽章:
0
5 [报告]
发表于 2006-11-14 19:08 |只看该作者
把print声明为static的就可以了,类成员函数还有一个属性是类域

论坛徽章:
0
6 [报告]
发表于 2006-11-15 09:38 |只看该作者
不错啊

论坛徽章:
0
7 [报告]
发表于 2006-11-15 15:28 |只看该作者
原帖由 converse 于 2006-11-14 19:08 发表
把print声明为static的就可以了,类成员函数还有一个属性是类域



请问还有别的办法吗?

la.lune  同志的方法在调用的时候pp->(4);好像会出错!

谢谢!!

论坛徽章:
0
8 [报告]
发表于 2006-11-15 15:31 |只看该作者
原帖由 cuicp 于 2006-11-15 15:28 发表



请问还有别的办法吗?

la.lune  同志的方法在调用的时候pp->(4);好像会出错!

谢谢!!

试试 (*pp)(4); 不要用pp->(4);

论坛徽章:
0
9 [报告]
发表于 2006-11-15 16:32 |只看该作者
>>typedef void (*p)(int i);

typedef void (A::*p)(int i);
也可以

论坛徽章:
0
10 [报告]
发表于 2006-11-15 16:54 |只看该作者
完整在VC6.0下建一个,控制台的工程,再去试吧.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP