c++ primer 第十四章习题

c++ primer 第十四章习题


练习14.1 具体实现有区别 优先级结合律和大致功能一样
练习14.2

ostream& operator<<(std::ostream& os, const Sales_data& item){
	os << item.isbn() << " " << item.units_sold << " " 
	   << item.revenue << " " << item.avg_price();
	return os;
}

Sales_data& 
Sales_data::operator+=(const Sales_data& rhs){
	this->combine(rhs);
	return *this;
}

Sales_data 
operator+(const Sales_data& lhs, const Sales_data& rhs){
	Sales_data sum = lhs;
	sum.combine(rhs);
	return sum;
}

练习14.3(a) 都不是 (b)string © vector (d) string
练习14.4 (a) F (b) T © T (d) T (e) F (f) F (g) F (h) T
练习14.7

ostream& operator<<(ostream& os, const String& s) {
	auto p = s.elements;
	do {
		os << *p;
	}while(++p != s.end);
	return os;
}

练习14.9

istream& operator>>(std::istream& in, Sales_data& item){
	double price;
	in >> item.bookNo >> item.units_sold >> price;
	if(in)
		item.revenue = item.units_sold*price;
	else
		item = Sales_data();
	return in;
}

练习14.10 (a)正确输入 (b)输入错误返回默认初始化结果
练习14.11 没有处理输入错误的情况
练习14.13 没有了
练习14.14 避免了一个临时对象的计算
练习14.29 const版本的对象不可变而递增递减是要改变对象的。
练习14.31 使用合成版本的即可。
练习14.33 和函数的操作数一样多
练习14.34

class judge
{
public:
	judge()=default;
	int operator()(bool a, int b, int c) {
		return a?b:c;
	}
	
};

练习14.35

class getString{
public:
	getString(istream& is):in(is){}
	string operator()() {
		string s;
		getline(in,s);
		if(in)
			return s;
		else
			return "";
	}
private:
	istream& in;
};

练习14.37

class equals
{
public:
	equals(int v):value(v){};
	bool operator()(int k) {
		return value == k;
	}
private:
	int value;
};

int main() {
	vector<int> vi = {1,2,3,4,5,6,3,5,2};

	replace_if(vi.begin(),vi.end(),equals(2),22222);
	for(int x : vi)
		cout << x<< ' ';
	return 0;
}

练习14.43

class equals
{
public:
	equals(int v):value(v){};
	bool operator()(int k) {
		return value == k;
	}
private:
	int value;
};

int main() {
	vector<int> vi = {3,6,9};
	auto r = find_if(vi.begin(),vi.end(),bind(modulus<int>(),54,placeholders::_1));
	if(r == vi.end()) cout << "Yes"<<endl;
	else cout << "No"<<endl;
	return 0;
}

练习14.46 需要,可能会导致意料不到的计算结果。
练习14.47 第一个不正确 第二个正确
练习14.50 第一个存在二义性,因为有多个可行的转换。第二个可行因为只有一个精准匹配的转换。
练习14.51 第一个。因为内置转换优先级高。
练习14.52 第一个有二义性。第二个可以,使用的是LongDouble的。
练习14.53 不合法。double d = static_cast(s1)+3.14;

猜你喜欢

转载自blog.csdn.net/qq_25037903/article/details/82918682