c++ - 模板类的非模板函数友元

标签 c++ templates friend

有人可以解释一下我做错了什么吗?这是我从编译器得到的错误。

非常感谢

1>------ Build started: Project: Ch16, Configuration: Release Win32 ------
1>  p643_inclusion.cpp
1>  p643_inclusion_main.cpp
1>  p643_print.cpp
1>p643_print.cpp(5): error C2065: 'T1' : undeclared identifier
1>p643_print.cpp(5): error C2065: 'T2' : undeclared identifier
1>p643_print.cpp(6): warning C4552: '<<' : operator has no effect; expected operator with side-effect
1>p643_print.cpp(7): warning C4552: '<<' : operator has no effect; expected operator with side-effect
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

p643_inclusion.h

#ifndef P643H
#define P643H

template< class T1, class T2> class Car { 

    friend void  print (const Car<T1, T2> &c1);
    private:
        T1 Wheels;
        T2 DriversName;
    public:
        Car(): Wheels(4), DriversName("None") {}
        Car(T1, T2);
};



template <class T1, class T2> class Driver {
    private:
        T1 Name;
        T2 Surname;
    public:
        Driver(): Name("None"), Surname("None") {}
};


#include "p643_inclusion.cpp"

#endif

p643_inclusion.cpp

# ifndef P643CC
#define P643CC

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

template<class T1, class T2>
Car<T1, T2>::Car(T1 w, T2 d) {
    Wheels = w;
    DriversName = d;
}

#endif

p643_print.cpp

#include "p643_inclusion.h"
template< class T1, class T2> class Car;

void  print (const Car<T1, T2> &c1) {
    cout << c1.Wheels << endl;
    cout << c1.DriversName << endl;
    }

主要内容

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


int main()
{

    Car<int, string> myCar;
    Driver<string, string> myDriver;

    print(myCar);

    return 0;
}

最佳答案

您的函数实际上并不是非模板函数。

void  print (const Car<T1, T2> &c1) {
    cout << c1.Wheels << endl;
    cout << c1.DriversName << endl;
}

这是错误的。您能问问自己 T1 到底是什么吗?和T2


您应该将其实现为:

template<class T1, class T2>
void  print (const Car<T1, T2> &c1) {
    cout << c1.Wheels << endl;
    cout << c1.DriversName << endl;
}

您应该将其设为 friend :

template< class T1, class T2> class Car { 

    //choose different name for type params, because enclosing class 
    //already using T1, and T2
    template<class U, class V>
    friend void  print (const Car<U, V> &c1);

    //...

关于c++ - 模板类的非模板函数友元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5554844/

相关文章:

c++ - 计算位掩码,枚举 0

c++ - 有没有一种通用的方法可以用 C++ 检测文件写入错误?

c++ - 具有在编译时确定的参数数量的 Lambda 函数

c++ - 无法从好友类访问成员

c++ - 类模板和友元类

c++ - 更改 gcc/g++ 版本会导致段错误

c++ - 如何将二维 map 作为函数指针传递

c++ - GCC模板参数模板

c++ - 具有默认参数和特化的模板

c++ - Friend 函数,期望 Primary Expression before 。 token