gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:20:45 24 4
gpt4 key购买 nike

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

非常感谢

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com