#include <iostream>
// overloading "operator () " outside class
//////////////////////////////////////////////////////////
class Rectangle
{
public:
Rectangle(const int w, const int h)
: width(w), height(h)
{};
~Rectangle() {};
int& operator() (const size_t i);
public:
int width;
int height;
};
//////////////////////////////////////////////////////////
int &
Rectangle::operator()(const size_t i)
{
if (i == 0)
return width;
else
return height;
}
//////////////////////////////////////////////////////////
std::ostream&
operator<< (std::ostream& os, const Rectangle& rec)
{
os << rec.width << ", " << rec.height;
return os;
}
//////////////////////////////////////////////////////////
int main()
{
Rectangle a(40, 10);
std::cout
<< "w = " << a(0) << std::endl // 输出 40
<< "h = " << a(1) << std::endl // 输出 10
;
return 0;
}
原文:https://www.cnblogs.com/alexYuin/p/11965912.html