C++Primer第14章:重载运算符和类型转换(部分解答)

C++Primer第14章:重载运算符和类型转换(部分解答),第1张

C++Primer第14章:重载运算符和类型转换(部分解答) 前提

这几天后就回家了,所以加快进度了,很多没做的都是要以前写的程序基础上加的,但是这些程序我没保存-.-

14.1节练习

14.1

不同点:
重载运算符必须具有至少一个class或者枚举类型的 *** 作数
重载运算符不保证 *** 作数的求值顺序,例如对&&和||的重载版本不再具有“短路求值”的特性,两个 *** 作数都要进行求值,而且不规定 *** 作数的求值顺序。
相同点:
对于优先级和结合性及 *** 作数的数目不变。

14.2

不想写-.-

14.3

(a)"cobble"=="stone" //内置版本
(b)svec1[0]==svec2[0] //string的重载版本
(c)svec1==svec2    //vector的重载版本
(d)svec1[0]=="stone" //用了string的重载版本

14.4

(a)%通常定义为非成员
(b)%=通常定义为类成员,因为它会改变对象的状态
(c)++通常定义为类成员,因为它会改变对象的状态
(d)->必须定义为类成员,否则编译出错
(e)<<通常定义为类成员
(f)&&通常定义为非成员
(g)==通常定义为非成员
(h)()必须定义为类成员,否则编译报错

14.5

 不想写
14.2.1节练习

14.6

ostream& operator << (ostream &output, sales_data &s)//对重载运算符<<进行定义
{
	//output << s.bookno << " "<< s.units_sold << " " << s.revenue << " " << s.price << endl;
	output << s.bookno << " " << s.units_sold << " " << s.revenue << " " << s.avg_price() << endl;
	return output;
}

14.7

不想写-.-

14.8

不想写-.-
14.2.2节练习

14.9

istream& operator >>(istream &input, sales_data &s)//对重载运算符>>进行定义
{
	input >> s.bookno >> s.units_sold >> s.price;
	if (input)
	{
		s.revenue = s.units_sold * s.price;
	}
	return input;
}

14.10

(a)0-201-999990- 10 24.95
(b) 10 24.95 0-210-99999-9
重载错位?

14.11

istream operator>>(istream&in,Sales_data&s){
double price;
in>>s.bookNo>>s.units_sold>>price;
s.revenue=s.units_sold*price;
return in;
}
如果输入错误会发生什么?没有判断输入数据的正确性

14.12

不想写-.-
14.3节练习

14.13

可以实现一个减法运算符

14.14

性能上没有优势,但是可读性更好?

14.15

不想做-.-

14.16

#include
#include
#include
#include
#include
using namespace std;
class StrBlob {
public:
	typedef std::vector::size_type size_type;
	StrBlob();
	StrBlob(std::initializer_list i1);
	size_type size() const { return data->size(); };
	bool empty() const {
		return data->empty();
	};
	void push_back(const std::string& t) { data->push_back(t); };
	void push_back(string&&);
	void pop_back();
	//元素访问
	std::string& front() const {
		return data->front();
	}
	std::string& back() const {
		return data->back();
	}
	std::shared_ptr> get_data() const {
		return data;
	}
private:
	std::shared_ptr>data;
	void check(size_type i, const std::string& msg) const;

};
bool operator==(const StrBlob& a, const StrBlob& b) {
	return a.get_data() == b.get_data();
}
bool operator!=(const StrBlob& a, const StrBlob& b) {
	return a.get_data() != b.get_data();
}
std::ostream&operator<<(std::ostream & out, StrBlob& a) {
	cout << a.get_data() << endl;
	return out;
}
inline StrBlob::StrBlob() :data(make_shared>()) {};
void StrBlob::push_back(string&& rhs) {
	cout << "移动" << endl;
	data->push_back(move(rhs));
	
}

int main() {
	//测试
	StrBlob a, b;
	string s = "hello";
	a.push_back(s);
	a.push_back("hello");
	cout << a << endl;
	cout << (a.get_data() == b.get_data()) << endl;
	return 0;
}

14.17

不想写-.-
14.3.2节练习

14.18

bool operator<(const StrBlob& a, const StrBlob& b) {
	return a.size() < b.size();
}

14.19

不想写-.-

14.4节练习

14.20

sales_data operator + (sales_data & lhs, sales_data & rhs)//定义重载运算符+函数,lhs和rhs是sales_item的对象
{
	sales_data ret;
	ret.bookno = lhs.bookno;
	ret.units_sold = lhs.units_sold + rhs.units_sold;
	ret.revenue = lhs.revenue + rhs.revenue;
	ret.avg_price();
	return ret;
}

14.21

sales_data& sales_data ::operator += (const sales_data &rhs)//
{
	units_sold += rhs.units_sold;
	revenue += rhs.revenue;
	return *this;//将this对象作为左值返回,*this相当于一个sales_item对象
}

14.22

StrVec& StrVec::operator=(std::initializer_list i1) {
	auto data = alloc_n_copy(i1.begin(), i1.end());
	free();
	elements = data.first;
	first_free = cap = data.second;
	return *this;
}

14.24

不想写

14.25

不想写
14.5节练习

14.26

string& operator[](const int index) {
		auto in = elements + index;
		return *in;
	}
14.6节练习

14.27

StrBlobPtr& operator--() {
		check(curr, "increment past end of StrBlobPtr");
		--curr;
		return *this;
	}
	StrBlobPtr& operator++() {
		check(curr, "increment past end of StrBlobPtr");
		++curr;
		return *this;
	}
	StrBlobPtr& operator++(int) {
		StrBlobPtr ret = *this;
		++* this;
		return ret;
	}
	StrBlobPtr& operator--(int) {
		StrBlobPtr ret = *this;
		--* this;
		return ret;
	}

14.28

不想写-.-

14.29

因为需要改变对象的值
14.8节练习

14.33

一个对象

14.34

#include
using namespace std;
class f_obj
{
public:
    int operator()(int val1,int val2,int val3)const
    {
        if(val1>0)return val2;
        else return val3;
    }
};

int main()
{
    f_obj f;
    int ans=f(1,2,3);
    cout< 

14.35

#include

using namespace std;
class PrintString
{
public:
    PrintString():str(new char(0)){};
private:
    string str;
public:
    string&operator()(istream&in){in>>str;return str;}
};
int main()
{
        PrintString s;
        s(cin);
        return 0;
}

14.36

#include
#include
using namespace std;
class PrintString
{
public:
    PrintString():str(new char(0)){};
private:
    vectorvec;
    string str;
public:
    string&operator()(istream&in)
    {
        in>>str;
        vec.emplace_back(str);
        return str;
    }
};
int main()
{
        PrintString s;
        s(cin);
        return 0;
}

14.37

#include
using namespace std;
class equals
{
public:
    bool operator()(const int val1,const int val2){return val1==val2;}
};
int main()
{
    int a=1,b=1;
    equals s;
    cout< 
14.8.1节练习 

14.38

#include
#include
using namespace std;
class eq
{
public:
    eq(int val=0):len(val){};
    bool operator()(const string&s){return len==s.size();};
private:
    int len;
};
int main()
{
    vectorvec={"111","2222","4444"};

    for(auto &num:vec)
    {
        for(int i=1;i<=10;i++)
        {
            eq eq(i);
            if(eq(num)==true)cout<<"len:"< 

14.39

#include
#include
using namespace std;
class eq
{
public:
    eq(int val=0):len(val){};
    bool operator()(const string&s){
        if(s.size()>10)return true;
        return len==s.size();
    }
private:
    int len;
};
int main()
{
    vectorvec={"111","2222","4444","2817438927158"};

    for(auto &num:vec)
    {
        for(int i=1;i<=10;i++)
        {
            eq eq(i);
            if(eq(num)==true)cout<<"len:"< 

14.40

不想写-.-

14.41

更加方便,简洁?
14.8.2节练习

14.42

#include
#include
using namespace std;

int main()
{
    int val=1024;
    vectorvec={1,2,3,4,1234,124,5,421,123421,52,315,212421,21214};
    vectorstr={"pooh","hello"};
    int count=0;
    greaterg;
    for(auto &num:vec)
    {
        if(g(num,val))count++;
    }
    cout<eq;

    for(auto &num:str)
    {
        if(eq(num,"pooh")==false)
        {
            cout<mul;
    for(auto &num:vec)
    {
        num=mul(num,2);
        cout< 

14.43

#include

using namespace std;

int main()
{
    int a=100;
    vectorans={1,2,3,4,5,1200,200};
    modulusmod;
    for(auto &num:ans)
    {
        if(mod(num,a)==0)cout< 
14.8.3节练习 

14.44

#include
using namespace std;

int main()
{
        map>biops=
        {
            {
              "+",plus()
            },
            {
                "-",std::minus()
            },
            {
                "/",divides()
            },
            {
                "*",[](int i,int j){return i*j;}
            },
            {
                "%",modulus()
            }
        };
        int a,b;
        string ops;
        while(1)
        {
            cin>>a>>ops>>b;
            cout< 
14.9.1节练习 

14.45

explicit operator string()const
	{
		return bookno;
	}
	explicit operator double()const 
	{
		return revenue;
	}

14.46

应该声明,需要显示,这样不会被隐式转换

14.47

struct
{
	operator const int();//表示接受const int的对方才可以使用
	operator int() const;//表示不可更改对象的值
};

14.48

应该要声明成explicit,我们需要在条件表达式中使用他们

14.49

不想写-.-
14.9.2节练习

14.50

struct LongDouble{
	LongDouble(double=0.0);
	operator double();
	operator float();
}
LongDouble ldObj;
int ex1=ldObj;//二义性
float ex2=ldObj;//正确

14.51

void calc(int);
void calc(LongDouble);
double dval;
calc(dval);
优先调用void calc(int)函数,因为是标准类型转化
14.9.3节练习

14.52

struct LongDouble{
	LongDouble operator+(const SmallInt&);
};
LongDouble operator+(LongDouble&,double);
SmallInt si;
LongDouble ld;
ld=si+ld;由于LongDouble不能转换成SmallInt,所以SmallInt的operator+不可行,由于也不可以SmallInt转换成LongDouble,所以LongDouble也不可行,由于SmallInt 可以转换成int,LongDouble可以转换成float和double,所以内置operator+(int,float)和operator+(int ,double)都可行,于是产生二义性
ld=ld+si;//与上面分析类似,但是LongDouble的成员operator+达到精确匹配,于是可以直接匹配。

14.53

SmallInt s1;
double d=s1+3.14;
内置operator+(int,double)可行,operator+(SmallInt,SmallInt(3.14))可行,于是有二义性,所以可以double d=s1+SmallInt(3.14);

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5690913.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存