习题14-31
因为在这个类中我们不需要申请或管理内存,因此使用合成版本就足够;
习题14-32
class StrBlobPtr_pointer
{
public:
StrBlobPtr_pointer() = default;
StrBlobPtr_pointer(StrBlobPtr* p) : pointer(p) { }
StrBlobPtr& operator *() const;
StrBlobPtr* operator->() const;
private:
StrBlobPtr* pointer = nullptr;
};
StrBlobPtr&
StrBlobPtr_pointer::operator *() const
{
return *pointer;
}
StrBlobPtr*
StrBlobPtr_pointer::operator ->() const
{
return pointer;
}
习题14-33
重载运算符函数的参数数量和该运算符作用的运算对象的数量一样多。函数调用运算符()最多可以传256个参数,因此在重载时,最多也能接受256个参数用作运算。
习题14-34
class ift
{
public:
int operator()(int a, int b, int c)
{
return (a==5) ? b: c;
}
};
习题14-35
class PrintString
{
public:
PrintString (istream& i=cin) : is (i) { }
string& operator()()const
{
string str;
getline(is,str);
return is?str:string();
}
private:
istream& is;
};
习题14-36
#include <iostream>
#include<string>
#include<vector>
using namespace std;
class PrintString
{
public:
PrintString(istream& i = cin) : is(i) { }
string operator()()const
{
string str;
getline(is, str);
return is ? str : string();
}
private:
istream& is;
};
void main()
{
PrintString ps;
vector<string> vec;
string tem = ps();
while(!tem.empty())
{
vec.push_back(tem);
tem = ps();
}
for (const auto &str : vec) cout << str << " ";
cout << endl;
}
习题14-37
class Equal
{
public:
Equal(int n) :v(n) {}
bool operator() (int num)
{
return v == num;
}
private:
int v;
};
void main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };
replace_if(vec.begin(), vec.end(), Equal(2), 10);
for (auto i : vec) {
cout << i << " ";
}
cout << endl;
}
习题14-38
class isEqual
{
public:
isEqual(int n = 1) :sz(n) {};
bool operator()(string str) { return str.size() == sz; };
int sz;
};
void main()
{
vector<isEqual> evec;
map<int, int> m;
for (int i = 1; i < 11; ++i)
{
evec.push_back(isEqual(i));
evec[i - 1].sz = i;
m[i] = 0;
}
ifstream ifs ("data.txt");
string word;
while (ifs >> word)
{
for (int i = 0; i < 10; ++i)
if (evec[i](word))
++m[evec[i].sz];
}
for (auto s : m)
cout << s.first << " " << s.second << endl;
}
习题14-39
class isRange
{
public:
isRange(int v1,int v2=0) :lower(v1),upper(v2) {};
bool operator()(string str);
int upper;
int lower;
};
bool isRange::operator()(string str)
{
if (upper == 0)
return str.size() >= lower;
else
return (str.size() >= lower)&&(str.size() <= upper);
};
void main()
{
isRange iR1(1, 9), iR2(10);
map<string, int> m;
m["1-9"] = 0;
m["10-"] = 0;
ifstream ifs ("data.txt");
string word;
while (ifs >> word)
{
if (iR1(word))
++m["1-9"];
if (iR2(word))
++m["10-"];
}
for (auto s : m)
cout << s.first << " " << s.second << endl;
}
习题14-40
太久了,略;