C++,非类型参数模板,报错:该符号在函数 _main 中被引用!求高人指点~

2025-05-12 20:00:02
推荐回答(1个)
回答1:

                friend int area(Scr &); //这里的area不是函数模板
template int area(Scr  &s)//这里的area是函数模板

二者是不同的东西,area(my_Scr)调用的是前者,而前者没有定义


解决方法是在类定义之前前向声明area函数模板(而这又需要前向声明Scr类),如下

#include
#include
using namespace std;

template
class Scr;

template int 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;

};
template int 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;
}