猿问

如果需要函数指针数组接收参数,这个该怎么操作呢?

class Base{
private:
int x;
int y;
public:
Base();
Base(int x,int y);
virtual void draw();
void move();
};

class Poit :virtual public Base{
public:
Poit();
Poit(int x,int y);
void draw();

};

class Line :virtual public Base{
private:
int a;
int b;
public:
Line();
Line(int a,int b,int x,int y);
void draw();
};

class Circle :virtual public Base{
private:
int r;
public:
Circle();
Circle(int x,int y,int r);
void draw();
};

class Graphics :public Poit,public Line, public Circle{
private:
static int i;
void (*pf[6])();
public:

void task(Poit *p); void task(Line *l);
void task(Circle *c);
void draw();
};
int Graphics::i=0;

#include <iostream.h>#include "Graphics.h"
Base::Base()
{
x=0;
y=0;
}

Base::Base(int x,int y){
this->x=x;
this->y=y;
}
void Base::move()
{
cout<<"将画笔移动到("<<x<<","<<y<<"),";
}

Poit::Poit():Base(0,0){
}

Poit::Poit(int x,int y):Base(x,y){
}

void Poit::draw(){
Base::move();
cout<<"画一个点"<<endl;
}

Line::Line():Base(0,0){
a=0;
b=0;
}

Line::Line(int a,int b,int x,int y):Base(x,y){
this->a=a;
this->b=b;
}

void Line::draw(){
Base::move();
cout<<"画一条到("<<a<<","<<b<<")的直线"<<endl;
}

Circle::Circle():Base(0,0){
r=0;
}

Circle::Circle(int x,int y,int r):Base(x,y){
this->r=r;
}

void Circle::draw(){
Base::move();
cout<<"画一个半径"<<r<<"的圆"<<endl;
}

void Graphics::draw(){
int n;
for(n=0;n<i;n++)
{
cout<<"第"<<n<<"步:";
(*pf[i])();
}
}

void Graphics::task(Poit *p){
pf[i]=p->draw;
}
void Graphics::task(Line *l)
{
pf[i]=l->draw;
}
void Graphics::task(Circle *c)
{
pf[i]=c->draw;
}

#include <iostream.h>#include "Graphics.h"
int main(){
Graphics g;
g.task(new Poit(3,5));
return 0;
}

MM们
浏览 402回答 2
2回答

缥缈止盈

#include <stdio.h>void print(char *srt){printf("%s\n",srt);}void (*p)(char *str);//函数指针int main(){p=print;//把要指向的函数给函数指针p("Hello World!");//传进参数return 0;}//简单例子

叮当猫咪

void (*array[10])(void)array[10]--->就是函数指针数组将对应的函数名赋值给数组就可以了比如这么个函数int fun(int a)array[0] = fun;就这样就可以了。你试试吧
随时随地看视频慕课网APP
我要回答