【C++ Primer | 13】课后习题答案

博客记录了节目与章节相关练习,包含13.1.4节目练习,如练习13.14、13.15等,还有13.2节练习及13.2.2练习,如练习13.27。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

13.1.4节目练习

  1. 练习13.14
#include <iostream>
using namespace std;

class numbered
{
private:    
    static int seq;
public:
    numbered() { mysn = seq++; }
    int mysn;
};

int numbered::seq = 0;

void f(numbered s) 
{ 
    cout << s.mysn << endl; 
}

int main()
{
    numbered a, b = a, c = b;
    f(a);
    f(b);
    f(c);
}
  1. 练习13.15
#include <iostream>
using namespace std;

class numbered
{
private:
	static int seq;
public:
	numbered() { mysn = seq++; }
	numbered(const numbered &n ) { mysn = seq++; }

	int mysn;
};

int numbered::seq = 0;

void f(numbered s)
{
	cout << s.mysn << endl;
}

int main()
{
	numbered a, b = a, c = b;
	f(a);
	f(b);
	f(c);
}
  1. 练习13.15
#include <iostream>
using namespace std;

class numbered
{
private:
	static int seq;
public:
	numbered() { mysn = seq++; }
	numbered(const numbered &n ) { mysn = seq++; }

	int mysn;
};

int numbered::seq = 0;

void f(numbered &s)
{
	cout << s.mysn << endl;
}

int main()
{
	numbered a, b = a, c = b;
	f(a);
	f(b);
	f(c);
}

13.2节练习

#include <string>

class HasPtr {
public:
    HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) {}
    HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i) {}
    HasPtr& operator=(const HasPtr &hp) 
    {
        auto new_p = new std::string(*hp.ps);
        delete ps;
        ps = new_p;
        i = hp.i;
        return *this;
    }
    ~HasPtr() { delete ps;} 
private:
    std::string *ps;
    int i;
};

13.2.2练习

  • 练习13.27
#include <string>

class HasPtr {
public:
    HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0), use(new size_t(1)) {}
    HasPtr(const HasPtr& hp) : ps(hp.ps), i(hp.i), use(hp.use) { ++* use; }
    HasPtr& operator=(const HasPtr& rhs);
private:
    std::string* ps;
    int i;
    size_t* use;
};

HasPtr& HasPtr::operator=(const HasPtr& rhs)
{
    ++* rhs.use;
    if (-- * use == 0)
    {
        delete ps;
        delete use;
    }
    ps = rhs.ps;
    i = rhs.i;
    use = rhs.use;
    return *this;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值