qfedu-cpp-level/day7/d1.cpp

45 lines
651 B
C++
Raw Normal View History

2023-08-01 18:51:53 +08:00
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
template <typename T>
T &maxVal(T &a, T &b)
{
return a > b ? a : b;
}
class A
{
friend A &maxVal<A>(A &a, A &b); // 模板特化的友元函数,用于访问私有成员
private:
int x;
public:
A(int x) : x(x) {}
void show()
{
cout << "x = " << x << endl;
}
};
// 具体化函数模版的重载
template <>
A &maxVal<A>(A &a, A &b) // 模板特化
{
if (a.x > b.x)
return a;
return b;
}
int main()
{
A a1(20), a2(50);
// A &b = maxVal<A>(a1, a2);
A &b = maxVal(a1, a2);
b.show();
return 0;
}