神秘博客

C++ Primer Plus [第六版]第18章编程练习题答案

1

#include <iostream>
#include <initializer_list>

template <typename T>
T average_list(std::initializer_list<T> f);

int main()
{
  using namespace std;
  auto q = average_list({ 15.4,10.7,9.0 });
  cout << q << endl;
  cout << average_list({ 20,30,19,17,45,38 }) << endl;
  auto ad = average_list<double>({ 'A',70,65.33 });
  cout << ad << endl;


  system("pause");
  return 0;
}

template <typename T>
T average_list(std::initializer_list<T> f)
{
  T tot = 0;
  for (auto p = f.begin(); p != f.end(); p++)
    tot += *p;

  return tot;
}

2

#include <iostream>
#include <string>

class Cpmv
{
public:
  struct Info
  {
    std::string qcode;
    std::string zcode;
  };
private:
  Info *pi;
public:
  Cpmv();
  Cpmv(std::string q, std::string z);
  Cpmv(const Cpmv &cp);
  Cpmv(Cpmv &&mv);
  ~Cpmv();
  Cpmv &operator=(const Cpmv &cp);
  Cpmv &operator=(Cpmv &&mv);
  Cpmv operator+(const Cpmv &obj) const;
  void Display() const;
};

Cpmv::Cpmv()
{
  std::cout << "默认构造函数\n";
  pi = new Info;
}

Cpmv::Cpmv(std::string q, std::string z)
{
  std::cout << "有参数构造函数\n";
  pi = new Info;
  pi->qcode = q;
  pi->zcode = z;
}

Cpmv::Cpmv(const Cpmv &cp)
{
  std::cout << "复制构造函数\n";
  pi = new Info;
  pi->qcode = cp.pi->qcode;
  pi->zcode = cp.pi->zcode;
}

Cpmv::Cpmv(Cpmv &&mv)
{
  std::cout << "移动构造函数\n";
  pi = mv.pi;
  mv.pi = nullptr;
}

Cpmv::~Cpmv()
{
  std::cout << "析构函数\n";
  delete pi;
}

Cpmv &Cpmv::operator=(const Cpmv &cp)
{
  std::cout << "复制赋值函数\n";
  if (this == &cp)
    return *this;
  delete pi;
  pi = new Info;
  pi->qcode = cp.pi->qcode;
  pi->zcode = cp.pi->zcode;

  return *this;
}

Cpmv &Cpmv::operator=(Cpmv &&mv)
{
  std::cout << "移动赋值函数\n";
  if (this == &mv)
    return *this;
  delete pi;
  pi = mv.pi;
  mv.pi = nullptr;

  return *this;
}

Cpmv Cpmv::operator+(const Cpmv &obj) const
{
  std::cout << "重载+运算符\n";
  Cpmv temp;
  temp.pi = new Info;
  temp.pi->qcode = pi->qcode + obj.pi->qcode;
  temp.pi->zcode = pi->zcode + obj.pi->zcode;

  return temp;
}

void Cpmv::Display() const
{
  std::cout << pi->qcode << std::endl;
  std::cout << pi->zcode << std::endl;
}

int main()
{
  using namespace std;
  Cpmv s1;
  Cpmv s2("神秘", "12345");
  s1 = s2;
  Cpmv s3(s1);
  Cpmv s4(s1 + s2);
  s3 = s1 + s2;

  s1.Display();
  s2.Display();
  s3.Display();
  s4.Display();

  system("pause");
  return 0;

}

3

#include <iostream>

long double sum_value() { return 0; }

long double tot = 0;
template <typename T,typename... Args>
long double sum_value(const T &value, const Args&... args)
{
  tot += value;
  sum_value(args...);

  return tot;
}

int main()
{
  using namespace std;

  cout << sum_value(1.5, 6, 7, 3, 4, 2.6, 48.5) << endl;

  system("pause");
  return 0;
}

4.

程序清单不对所以完结撒花

版权说明:
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

觉得文章有用就请我吃包辣条吧

微信扫一扫打赏