繁体   English   中英

具有相同类型的模板类的模板函数好友

[英]template function friend of template class with same Type

下面显然有一个外部代码,如果有人可以指出如何避免它,将不胜感激。

谢谢

1> ------构建开始:项目:Ch16,配置:调试Win32 ------
1> p657_b_print.cpp
1> p657_b_main.obj:错误LNK2019:未解析的外部符号“ void __cdecl compare <int>(int&,class Car <int>&)”(?? $ compare @ H @@ YAXAAHAAV?$ Car @ H @@@ Z )在函数_main中引用
1> \\ na-13 \\我的文档\\ Visual Studio 2010 \\ Projects \\ Ch16 \\ Debug \\ Ch16.exe:致命错误LNK1120:1无法解析的外部
==========构建:0成功,1失败,0最新,跳过0 ==========

p657_b.h

#ifndef P657H
#define P657H

template< class T> class Car; 
template<class T1> void  compare(T1&, Car<T1>&);

template< class T> class Car { 
    friend void  compare<T> (T&, Car<T>&);

private:
    T Wheels;

public:
    Car(): Wheels(4)  {}
    Car(T);
};

#include "p657_b.cpp"
#include "p657_b_print.cpp"

#endif

p657_b.cpp

#ifndef P643CC
#define P643CC

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
#include "p657_b.h"

template<class T> Car<T>::Car(T w) {
    Wheels = w;
}
#endif

p657_b_print.cpp

#ifndef p657_CC
#define p657_CC
#include "p657_b.h"
#include<iostream>
using namespace std;

template <class T>
void compare(T &iv1, Car<T> &c1) {
    cout << iv1 << endl;
    cout << c1.Wheels << endl;
}

#endif

p657_b_main.cpp

#include "p657_b.h"
#include<iostream>
#include<string>
using namespace std;

int main()
{
    Car<int> myCar;
    int iv = 5;
    compare(iv, myCar);

    return 0;
}

整个模板定义必须在一个文件中。 您应该合并_b.cpp_b.h并在程序中包括完整的模板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM