C++中关于无法无法解析外部错误的解决方案

来源:互联网 发布:网络机顶盒那个牌子的好 编辑:程序博客网 时间:2024/05/18 02:49

首先 为什么写这个博客,前几日遇到了一个问题,就是在用类模板写堆的时候,出现了这个问题,当时花了好久,解决了那个问题,今天在看C++Primer Plus的时候在函数指针的时候,出现了相同的问题。

下面上代码

#include<iostream>using namespace std;const double *f1(const double ar[], int n);const double *f2(const double [],int);const double *f3(const double *,int);void main(){const double *(*p1)(const double ar[], int n) = f1;auto p2 = f2;const double *(*p[3])(const double ar[],int n) = {f1,f2,f3};auto pb = p;cout<<p1<<endl<<p2<<endl<<pb[1]<<" "<<pb[2]<<" "<<pb[3]<<endl;}/*const double *f1(const double ar[], int n){return ar;}const double *f2(const double ar[], int n){return ar+1;}const double *f3(const double ar[], int n){return ar+2;}*/
这个会出现

1>C++.obj : error LNK2019: 无法解析的外部符号 "double const * __cdecl f3(double const *,int)" (?f3@@YAPBNPBNH@Z),该符号在函数 _main 中被引用
1>C++.obj : error LNK2019: 无法解析的外部符号 "double const * __cdecl f2(double const * const,int)" (?f2@@YAPBNQBNH@Z),该符号在函数 _main 中被引用
1>C++.obj : error LNK2019: 无法解析的外部符号 "double const * __cdecl f1(double const * const,int)" (?f1@@YAPBNQBNH@Z),该符号在函数 _main 中被引用
1>C:\Users\zxx\documents\visual studio 2010\Projects\Test1\Debug\Test1.exe : fatal error LNK1120: 3 个无法解析的外部命令
这是为什么呢? 可以这样想 你只是申明 了有三个函数,然后用一个函数的数组指针指向了这三个函数,但是问题出来了,这个逻辑上并没有错误,为啥报错呢?

我也没有想明白,于是加上了实现 就没有错误了,看来还是因为指向的函数没有实现,结果导致空指向??

另外 在做类模板的时候 出现问题的原因也是因为没有实现,只是一个抽象的模板,而你传递的时候,必须要是个实例化如<int>的类或者方法,所以建议把模板和实现放在一起

这样就不会报错了。但是这样做的话,和STL中的类模板的实现就有差距,这个以后有时间研究在写一个博客。

阅读全文
0 0