部分习题解答:
14.1:
不同点: 重载运算符必须具有至少一个class或枚举类型的操作数。
重载运算符不保证操作数的求值顺序,例如对&&和||的重载版本不再具有“短路求值”的特性,两个操作数都要求值,而且不规定操作数的求值顺序。
相同点: 对于优先级和结合性级操作数的数目都不变。
14.2:
class Sales_data
{
friend std::istream& operator>>(std::istream&, Sales_data &);
friend std::ostream& operator<<(std::ostream&, const Sales_data&);
public:
Sales_data& operator+=(const Sales_data&);
};
Sales_data operator+(const Sales_data&, const Sales_data&);
14.26:
class StrBlob {
public:
string & operator[](size_t n) { return data[n]; };
const string& operator[](size_t n) const { return data[n]; };
};
//其他类都类似
14.27:
class StrBlobPtr{
public:
StrBlobPtr& operator++();
StrBlobPtr& operator--();
StrBlobPtr operator++(int);
StrBlobPtr operator--(int);
};
StrBlobPtr& StrBlobPtr::operator++()
{
check(curr, " increment past end of StrBlobPtr ");
++curr;
return *this;
}
StrBlobPtr& StrBlobPtr::operator--()
{
--curr;
check(-1, " decrement past begin of StrBlobPtr ");
return *this;
}
StrBlobPtr StrBlobPtr::operator++(int)
{
StrBlobPtr ret = *this;
++*this;
return ret;
}
StrBlobPtr StrBlobPtr::operator--(int)
{
StrBlobPtr ret = *this;
--*this;
return ret;
}
14.28:
class StrBlobPtr{
public:
friend StrBlobPtr operator+(int n);
friend StrBlobPtr operator-(int n);
};
StrBlobPtr StrBlobPtr::operator+(int n)
{
auto ret = *this;
ret.curr += n;
return ret;
}
StrBlobPtr StrBlobPtr::operator-(int n)
{
auto ret = *this;
ret.curr -= n;
return ret;
}
14.29:
因为不论是递减或递增都会改变对象的值,所以不定义const版本
14.30:
class StrBlobPtr{
public:
string & operator*() const {
auto p = check(curr, "dereference past end");
return (*p)[curr];
}
string* operator->() const {
return &(this->operator*());
}
};
class ConstStrBlobPtr {
public:
const string & operator*() const {
auto p = check(curr, "dereference past end");
return (*p)[curr];
}
const string* operator->() const {
return &(this->operator*());
}
};
14.31:
StrBlobPtr有两个数据成员,分别为weak_ptr<vector<string>>和size_t类型的,前者定义了自己的拷贝操作,后者为内置类型,默认的拷贝语意即可
14.32:
class MyStrBlob{
public:
string* operator->() const {
return ptr->operator();
}
private:
StrBlobPtr *ptr;
}
14.33:
0个或多个
14.34:
class Ifthenelse {
public:
Ifthenelse(){}
Ifthenelse(int v1,int v2,int v3):val1(v1),val2(v2),val3(v3){}
int operator()(int v1, int v2, int v3)
{
return v1 ? v2 : v3;
}
private:
int val1, val2, val3;
};
14.35:
class Readstring {
public:
Readstring(istream &is = cin) :is(is) {}
string operator()()
{
string line;
if (!getline(is, line))
{
line = " ";
}
return line;
}
private:
istream &is;
};
14.36:
void testReadstring()
{
Readstring re;
vector<string> vec;
while (true)
{
string line = re();
if (!line.empty())
{
vec.push_back(line);
}
else
break;
}
}
14.37:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class IntCompare {
public:
IntCompare(int v):val(v){}
bool operator()(int v) { return val == v; }
private:
int val;
};
int main()
{
vector<int> vec = { 1,2,3,4,5,5,4,3,2,1 };
const int oldval = 2;
const int newval = 200;
IntCompare intc(oldval);
replace_if(vec.begin(), vec.end(), intc, newval);
for (auto c : vec)
{
cout << c << " ";
}
system("pause");
return 0;
}
14.38:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class StrLenComp{
public:
StrLenComp(int l) :len(l) {}
bool operator()( const string &str) { return str.size() == len; }
private:
int len;
};
int main()
{
vector<string> vec;
string word;
while (cin >> word)
{
vec.push_back(word);
}
const int minlen = 1;
const int maxlen = 10;
for (int i = minlen; i <= maxlen; ++i)
{
StrLenComp slc(i);
cout << "len: " << i << ", cnt: " << count_if(vec.begin(), vec.end(), slc) << endl;
}
system("pause");
return 0;
}
14.39:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class StrLenBetween{
public:
StrLenBetween(int minl,int maxl) :minlen(minl),maxlen(maxl) {}
bool operator()(const string &str) { return str.size() >= minlen && str.size() <= maxlen; }
private:
int minlen,maxlen;
};
class StrLenNoshorter {
public:
StrLenNoshorter(int minl) :minlen(minl) {}
bool operator()(const string &str) { return str.size() >= minlen ; }
private:
int minlen;
};
int main()
{
vector<string> vec;
string word;
while (cin >> word)
{
vec.push_back(word);
}
StrLenBetween slb(1,9);
StrLenNoshorter sln(10);
cout << "len (1-9): " << count_if(vec.begin(), vec.end(), slb) << endl;
cout << "len (>10): " << count_if(vec.begin(), vec.end(), sln) << endl;
system("pause");
return 0;
}
14.40:
class IsShorter {
public:
bool operator()(const string &a, const string &b)
{
return a.size() < b.size();
}
};
class IsLong {
public:
IsLong(int ml):minlen(ml){}
bool operator()(const string &a)
{
return a.size() >= minlen;
}
private:
int minlen;
};
class Print {
public:
void operator()(const string &s) { cout << s << " "; }
};
void biggies(vector<string> &words, vector<string>::size_type sz)
{
elimDups(words);
IsShorter ish;
stable_sort(words.begin(), words.end(), ish);
IsLong isl(sz);
auto wc = find_if(words.begin(), words.end(), isl);
auto count = words.end() - wc;
cout << count << " " << make_plural(count, "word", "s") <<
" of length" << sz << " or longer" << endl;
Print p;
for_each(wc, words.end(), p);
cout << endl;
}
14.41:
在C++11中,lambda是通过匿名的函数对象来实现的,因此我们可以把lambda看作是对函数对象在使用方式上进行的简化。当代码需要一个简单的函数,并且这个函数并不会在其他地方被使用时,就可以使用lambda来实现,此时它所起的作用类似于匿名函数。但如果这个函数需要多次使用,并且它需要保存某些状态的话,使用函数对象更合适一些。
14.42:
(a) count_if(vec.begin(), vec.end(), bind2nd(greater<int>(), 1024));
(b) find_if(vec.begin(), vec.end(), bind2nd(not_equal_to, "pooh"));
(c) transform(vec.begin(), vec.end(),vec.begin(), bind2nd(multiplies<int>(), 2));
14.43:
bool divideAll(vector<int> vec, int dividenum)
{
return count_if(vec.begin(), vec,end(), bind1st(modulus<int>(), dividenum)) == 0;
}
14.44:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <map>
using namespace std;
map<string, function<int(int, int)>> binops = {
{ "+",plus<int>() },
{ "-",minus<int>() },
{ "*",multiplies<int>() },
{ "/",divides<int>() },
{ "%",modulus<int>() }
};
int main()
{
int a, b;
string op;
cin >> a >> op >> b;
cout << binops[op](a, b) << endl;
system("pause");
return 0;
}
14.45:
如果要转换成string,那么返回值应该是bookNo。
如果要转换成double,那么返回值应该是revenue。
14.46:
前者将对象转换成const int,在接受const int值的地方才能够使用。
后者将对象转换成int值,相对来说更加通用一些。
14.48:
应该,定义一个bool的类型转换运算符,可以用来检测数据成员是否有效;应该声明成explicit,因为我们有意要在表达式中使用它
14.50:
对于int ex1 = ldOb;,它需要把LongDouble类型转换成int类型,但是LongDouble并没有定义对应的类型转换运算符,因此它会尝试使用其他的来进行转换。题中给出的两个都满足需求,但编译器无法确定那一个更合适,因此会产生二义性错误。
对于foloat ex2 = ldObj;,它需要把LongDouble转换成float类型,而我们恰好定义了对应的类型转换运算符,因此直接调用operator float()即可。
14.51:
这里会优先调用void calc(int)函数。
因为double转换为int是标准类型转换,而转换为LongDouble则是转换为用户自定义类型,实际上调用了转换构造函数,因此前者优先。
14.52:
对于ld=si+ld,由于LongDouble不能转换为SmallInt,因此Smallint的成员operator+和friend operator都不可行。
由于Smallint不能转换为LongDouble,LongDouble的成员operator+和非成员operator+也都不可行。
由于SmallInt可以转换为int, LongDouble了可以转换为float和double,所以内置的operator+(int, float)和operator+(int, double)都可行,会产生二义性。
对于ld=ld+si,类似上一个加法表达式,由于Smallint不能转换为double,LongDouble也不能转换为SmallInt,因此SmallInt的成员operator+和两个非成员operator+都不匹配。
LongDouble的成员operator+可行,且为精确匹配。
SmallInt可以转换为int,longDouble可以转换为float和double,因此内置的operator+(float, int)和operator(double, int)都可行。但它们都需要类型转换,因此LongDouble的成员operator+优先匹配。
14.53:
内置类型的operator+(int double)可行,3.14可转换成int,再转换成SmallInt,所以SmallInt的operator+也是可行的,会产生二义性,应改成double d = s1 + SmallInt(3.14);