练习14.33:
重载的函数调用运算符接受的运算对象没有限制,可以没有,也可以1个或者多个
练习14.34:
class IfThenElse {
public:
//函数调用运算符
//假设接受int类的形参
int operator()(int a, int b, int c)
{
return a ? b : c;
}
//其他成员函数
//...
private:
//其他数据成员
//...
};
练习14.35:
本题的类与PrintString基本相同,一个是打印一个是读取
#include <iostream>
#include <string>
#include <errno.h>
using namespace std;
//类似PrintString
class ReadString {
public:
//构造函数
ReadString(istream& istr = cin) :is(istr) { }
//函数调用运算符
std::string operator()()
{
string line;
getline(is, line);
return line;
}
private:
//用于读入的目的流
istream& is;
};
//测试
int main()
{
system("pause");
return 0;
}
练习14.36:
#include <iostream>
#include <string>
#include <errno.h>
using namespace std;
#include <vector>
//类似PrintString
class ReadString {
public:
//构造函数
ReadString(istream& istr = cin) :is(istr) { }
//函数调用运算符
std::string operator()()
{
string line;
getline(is, line);
return line;
}
private:
//用于读入的目的流
istream& is;
};
//打印vector
void PrintVector(const vector<string>& v)
{
cout << "print vector:" << endl;
for (auto s : v)
{
cout << s << endl;
}
}
int main()
{
vector<string>v;
//创建对象
ReadString rd(cin);
string word;
cout << "save to vector:" << endl;
word = rd();
v.push_back(word);
word = rd();
v.push_back(word);
word = rd();
v.push_back(word);
PrintVector(v);
system("pause");
return 0;
}
结果:
练习14.37:
#include <iostream>
#include <string>
#include <errno.h>
using namespace std;
#include <vector>
class CompareValue{
public:
//构造函数
CompareValue(std::string str = std::string()) :s(str) { }
//函数调用运算符
bool operator()(std::string s1)
{
return s == s1;
}
private:
std::string s;
};
//测试
int main()
{
CompareValue cv("hello");
auto it = cv("hella");
if (it == true)
{
cout << "two numbers are equal" << endl;
}
else
{
cout << "two numbers are no equal" << endl;
}
system("pause");
return 0;
}
结果: