如果要严谨些,那得这么写
程序代码:
#include <cassert>
template<typename T>
class Point;
template<typename T>
double slope( const Point<T>& a, const Point<T>& b );
template<typename T>
class Point
{
public:
Point() : x_(), y_()
{
}
Point( T x, T y ) : x_(x), y_(y)
{
}
private:
T x_, y_;
friend double slope<>( const Point<T>& a, const Point<T>& b );
};
template<typename T>
double slope( const Point<T>& a, const Point<T>& b )
{
assert( a.x_ != b.x_ );
return (a.y_-b.y_)/(a.x_-b.x_);
}
#include <iostream>
using namespace std;
int main( void )
{
Point<int> point1(1,1);
Point<int> point2(2,2);
cout << slope(point1,point2) << endl;
return 0;
}
不要求那么严谨,可以
程序代码:
#include <cassert>
template<typename T>
class Point
{
public:
Point() : x_(), y_()
{
}
Point( T x, T y ) : x_(x), y_(y)
{
}
private:
T x_, y_;
template<typename U> friend double slope( const Point<U>& a, const Point<U>& b );
};
template<typename U>
double slope( const Point<U>& a, const Point<U>& b )
{
assert( a.x_ != b.x_ );
return (a.y_-b.y_)/(a.x_-b.x_);
}
#include <iostream>
using namespace std;
int main( void )
{
Point<int> point1(1,1);
Point<int> point2(2,2);
cout << slope(point1,point2) << endl;
return 0;
}
差别在于,第一段代码中 slope<int>是Point<int>的友元,slope<double>是Point<double>的友元,……
而第二段代码中,slope<int>、slope<double>……是Point<int>的友元,也是Point<double>的友元,……