这个代码是把Output函数作为一个地址来做的,不知道为什么编译的
时候一直给我报错,可是书上明明可以的啊
错误如下:C:\Users\ADMINI~1\AppData\Local\Temp\ccxuRVz9.o 函数作参数.cpp:(.rdata$.refptr._ZN3ICS6OutputE[.refptr._ZN3ICS6OutputE]+0x0): undefined reference to `ICS::Output'
C:\Users\Administrator\Desktop\collect2.exe [Error] ld returned 1 exit status
#include
using namespace std;
class ICS
{
private:
int a;
int b;
static void (*Output)(int a);
public:
ICS();
void show(void(*thevisit)(int))
{
Output = thevisit;
Output(a);
}
void show1()
{
show(output);
}
};
ICS::ICS()
{
cout << "the sum \n";
cin >> a;
cout << a;
}
void ICS::output(int a)
{
cout << "the number is " << a << endl;
}
int main()
{
ICS I;
I.show1();
return 0;
}
static void (*Output)(int a);
注意Output的O是大写的
#include<iostream>
using namespace std;
class ICS
{
private:
int a;
int b;
static void (*Output)(int a);
public:
ICS();
void show(void(*thevisit)(int))
{
Output = thevisit;
Output(a);
}
void show1()
{
show(Output);
}
void output(int a);
};
ICS::ICS()
{
cout << "the sum \n";
cin >> a;
cout << a;
}
void ICS::output(int a)
{
cout << "the number is " << a << endl;
}
int main()
{
ICS I;
I.show1();
return 0;
}
这么写可以编译通过。
楼上大小写的论调太搞笑了,问题的根源不是拼写,而是static void (*Output)(int a) 这样的写法是错误的,既然是function, 就要好好定义成static的成员函数而不是一个函数地址的成员变量,否则你在实现函数的时候ICS::Output肯等找不到类定义中对应的函数。
我出去了这个函数地址的成员变量的定义,加了一个静态的成员函数,就解决了问题。我已编译通过并正确运行了,请看以下代码:
#include "stdafx.h"
#include
using namespace std;
class ICS
{
private:
int a;
int b;
//static void(*Output)(int a); 不能这样定义,注释了
public:
ICS();
void show(void(*thevisit)(int))
{
/*Output = thevisit;
Output(a);*/
thevisit(a);
}
void show1()
{
show(Output);
}
static void Output(int a); //要这样定义成类的成员函数才行
};
ICS::ICS()
{
cout << "the sum \n";
cin >> a;
cout << a << endl; // 这里添加一个换行吧,否则输出出来太丑了
}
void ICS::Output(int a)
{
cout << "the number is " << a << endl;
}
int main()
{
ICS I;
I.show1();
return 0;
}