friend int area(Scr&); //这里的area不是函数模板
templateint area(Scr &s)//这里的area是函数模板
二者是不同的东西,area(my_Scr)调用的是前者,而前者没有定义
解决方法是在类定义之前前向声明area函数模板(而这又需要前向声明Scr类),如下
#include
#include
using namespace std;
template
class Scr;
templateint area(Scr &s);
template
class Scr{
friend int area(Scr&);
public:
Scr() : higth(M), width(N) { };
//Scr() = default;
int get_higth() { return M; }
int get_width() { return N; }
//int area() { return M*N; }
private:
int higth;
int width;
};
templateint area(Scr &s)
{
return s.higth*s.width;
}
int main(void)
{
Scr<6, 8> my_Scr;
cout << "my_Scr 's higth is:" << my_Scr.get_higth() << endl;
cout << "my_Scr's width is:" << my_Scr.get_width() << endl;
cout << "The area is :" << area(my_Scr)<< endl;
system("pause");
return 0;
}