【发布时间】:2022-01-13 12:58:04
【问题描述】:
所以我想声明一个函数 func(temp t1, temp t2) 并在 class temp 中使用它。但我不想将它定义为 class temp 的成员函数,主要是因为我希望其他函数能够访问 func 而无需使用 的任何对象温度。我知道可以通过将 func() 声明为 temp 的朋友,但是有没有办法为 temp 声明一种原型,所以我可以将它用作非成员函数 temp 的参数,然后再定义它吗?
template<typename Type>
class record
{
public:
Type data;
/*....some other memebers...*/
friend int rec_comp(const record& r1, const record& r2)
{
}
bool operator==(const record& r1, const record& r2)
{
if(rec_comp(r1, r2)==0)
return true;
else
return false;
}
/*...similar implementation for other relational operators ...*/
};
我想在类外声明函数rec_comp。
【问题讨论】:
-
你的意思是像
class Foo;吗?但它只适用于引用/指针。 -
那你有一个糟糕的实现设计。
-
是的。允许这样的事情吗?
-
@GauravShukla 然后请创建一个带有所需用例的小示例。但我也闻到了一些糟糕的设计
-
声明在类内作为友元函数,然后在类外define(实现)?无论如何,如果没有完整的类定义,您将无法调用该函数,因此不妨在类中将其声明为
friend函数。