练习题答案

练习6.1 试改写以下类,使它成为一个class template:

class example
{
public:
example(double min, double max);
example(const double* array, int size);
double& operator[](int index);
bool operator==(const example&) const;
bool insert(const double*, int);
bool insert(double);
double min() const { return _min; }
double max() const { return _max; }
void min(double);
void max(double);
int count(double value) const; private:
int size;
double* parray;
double _min;
double _max;
};

改写后:

template <typename elemType>
class example
{
public:
example(const elemType& min, const elemType& max);
example(const elemType* array, int size);
elemType& operator[](int index);
bool operator==(const example&) const;
bool insert(const elemType*, int);
bool insert(const elemType&);
elemType min() const { return _min; }
elemType max() const { return _max; }
void min(const elemType&);
void max(const elemType&);
int count(const elemType& value) const; private:
int _size;
elemType* _parray;
elemType _min;
elemType _max;
};

练习6.2 重新以template形式实现练习4.3的Matrix class,并扩充其功能,使它能够通过通过heap memory(堆内存)来支持任意行列大小。分配/释放内存的操作,请在constructor/destructor中进行。

Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
using namespace std; template <typename elemType>
class Matrix; template <typename elemType>
class Matrix
{
friend Matrix operator+ <elemType> (const Matrix&, const Matrix&);
template <typename elemType>
friend Matrix<elemType> operator* (const Matrix<elemType>&, const Matrix<elemType>&); public:
Matrix(int rows, int columns);
Matrix(const Matrix&);
~Matrix() { delete[] _matrix; }
Matrix& operator=(const Matrix&);
void operator+= (const Matrix&);
elemType& operator()(int row, int column)
{
return _matrix[row * cols() + column];
} const elemType& operator()(int row, int column) const
{
return _matrix[row * cols() + column];
} int rows() const { return _rows; }
int cols() const { return _cols; } bool same_size(const Matrix& m) const
{
return rows() == m.rows() && cols() == m.cols();
} bool comfortable(const Matrix& m) const
{
return (cols() == m.rows());
} ostream& print(ostream&) const; protected:
int _rows;
int _cols;
elemType* _matrix;
}; template <typename elemType>
inline ostream& operator<<(ostream& os, const Matrix<elemType>& m)
{
return m.print(os);
} template<typename elemType>
Matrix<elemType> operator+(const Matrix<elemType>& m1, const Matrix<elemType>& m2)
{
//确定m1和m2大小相同
Matrix<elemType> result(m1);
result += m2;
return result;
} template<typename elemType>
Matrix<elemType> operator * (const Matrix<elemType>& m1, const Matrix<elemType>& m2)
{
//m1的行数(row)必须等于m2的列数(column)
Matrix<elemType> result(m1.rows(), m2.cols());
for (int ix = 0;ix < m1.rows();++ix)
{
for (int jx = 0;jx < m1.cols();++jx)
{
result(ix, jx) = 0;
for (int kx = 0;kx < m1.cols();++kx)
{
result(ix, jx) += m1(ix, kx) * m2(kx, jx);
}
}
}
return result;
} template <typename elemType>
void Matrix<elemType>::operator+=(const Matrix& m)
{
//确定m1和m2的大小相同
int matrix_size = cols() * rows();
for (int ix = 0;ix < matrix_size;++ix)
{
(*(_matrix + ix)) += (*(m._matrix + ix));
}
} template <typename elemType>
ostream& Matrix<elemType> ::print(ostream& os) const
{
int col = cols();
int matrix_size = col * rows();
for (int ix = 0;ix < matrix_size;++ix)
{
if (ix % col == 0)
os << endl;
os << (*(_matrix + ix)) << ' ';
}
os << endl;
return os;
} template <typename elemType>
Matrix<elemType>& Matrix<elemType>::operator=(const Matrix& rhs)
{
if (this != &rhs)
{
_rows = rhs._rows;
_cols = rhs._cols;
int mat_size = _rows * _cols;
delete[] _matrix;
_matrix = new elemType[mat_size];
for (int ix = 0;ix < mat_size;++ix)
_matrix[ix] = rhs._matrix[ix];
}
return *this;
} template <typename elemType>
Matrix<elemType>::Matrix(int rows, int columns) :_rows(rows), _cols(columns)
{
int size = _rows * _cols;
_matrix = new elemType[size];
for (int ix = 0;ix < size;++ix)
_matrix[ix] = elemType();
} template <typename elemType>
Matrix<elemType>::Matrix(const Matrix& rhs)
{
_rows = rhs._rows;
_cols = rhs._cols;
int mat_size = _rows * _cols;
_matrix = new elemType[mat_size];
for (int ix = 0;ix < mat_size;++ix)
_matrix[ix] = rhs._matrix[ix];
} #endif main.cpp #include "Matrix.h"
#include <fstream> int main()
{
ofstream log("log.txt");
if (!log)
{
cerr << "can't open log file!\n";
return 0;
} Matrix<float> identity(4, 4);
log << "identity: " << identity << endl;
float ar[16] = { 1.,0.,0.,0.,0.,1.,0.,0.,
0.,0.,1.,0.,0.,0.,0.,1. }; for (int i = 0, k = 0;i < 4;++i)
{
for (int j = 0;j < 4;++j)
identity(i, j) = ar[k++];
}
log << "identity after set: " << identity << endl; Matrix<float> m(identity);
log << "m: memberwise initialized: " << m << endl; Matrix<float> m2(8, 12);
log << "m2: 8*12: " << m2 << endl;
m2 = m;
log << "m2 after memberwise assigned to m: "
<< m2 << endl; float ar2[16] = { 1.3,0.4,2.6,8.2,6.2,1.7,1.3,8.3,
4.2,7.4,2.7,1.9,6.3,8.1,5.6,6.6 }; Matrix<float> m3(4, 4);
for (int ix = 0, kx = 0;ix < 4;++ix)
for (int j = 0;j < 4;++j)
m3(ix, j) = ar2[kx++]; log << "m3: assigned random values: " << m3 << endl; Matrix<float> m4 = m3 * identity;
log << m4 << endl;
Matrix<float> m5 = m3 + m4;
log << m5 << endl; m3 += m4;
log << m3 << endl; return 0;
}

感谢https://www.cnblogs.com/lv-anchoret/p/8342842.htmlhttps://blog.csdn.net/mind_v/article/details/70228402 给出的友元重载解决方法。

end。

“巅峰诞生虚伪的拥趸,黄昏见证虔诚的信徒。”

#《Essential C++》读书笔记# 第六章 以template进行编程的更多相关文章

  1. 《Microsoft Sql server 2008 Internals》读书笔记--第六章Indexes:Internals and Management(1)

    <Microsoft Sql server 2008 Internals>索引文件夹: <Microsoft Sql server 2008 Internals>读书笔记--文 ...

  2. C primer plus 读书笔记第六章和第七章

    这两章的标题是C控制语句:循环以及C控制语句:分支和跳转.之所以一起讲,是因为这两章内容都是讲控制语句. 第六章的第一段示例代码 /* summing.c --对用户输入的整数求和 */ #inclu ...

  3. #《Essential C++》读书笔记# 第四章 基于对象的编程风格

    基础知识 Class的定义由两部分组成:class的声明,以及紧接在声明之后的主体.主体部分由一对大括号括住,并以分号结尾.主体内的两个关键字public和private,用来标示每个块的" ...

  4. C++ primer plus读书笔记——第7章 函数——C++的编程模块

    第7章 函数--C++的编程模块 1. 函数的返回类型不能是数组,但可以是其他任何一种类型,甚至可以是结构和对象.有趣的是,C++函数不能直接返回数组,但可以将数组作为结构或对象的组成部分来返回. 2 ...

  5. 《R语言实战》读书笔记-- 第六章 基本图形

    首先写第二部分的前言. 第二部分用来介绍获取数据基本信息的图形技术和统计方法. 本章主要内容 条形图.箱型图.点图 饼图和扇形图 直方图和核密度图 分析数据第一步就是要观察它,用可视化的方式是最好的. ...

  6. 《Python基础教程》 读书笔记 第六章 抽象 函数 参数

    6.1创建函数 函数是可以调用(可能包含参数,也就是放在圆括号中的值),它执行某种行为并且返回一个值.一般来说,内建的callable函数可以用来判断函数是否可调用: >>> x=1 ...

  7. 《利用python进行数据分析》读书笔记--第六章 数据加载、存储与文件格式

    http://www.cnblogs.com/batteryhp/p/5021858.html 输入输出一般分为下面几类:读取文本文件和其他更高效的磁盘存储格式,加载数据库中的数据.利用Web API ...

  8. Spring AOP (Spring 3.x 企业应用开发实战读书笔记第六章)

    从面相对象编程到面相切面编程,是一种代码组织方式的进化. 每一代的代码组织方式,其实是为了解决当时面对的问题.比如写编译器和写操作系统的时候的年代当然要pop,比如写界面的时候当然要oop,因为界面这 ...

  9. 《Java核心技术(卷一)》读书笔记——第六章:内部类

    1.      内部类的概念? 类中类 2.      为什么要用内部类? 内部类的方法可以访问外部类的实例域 内部类对外部类的同一个包中的类实现了隐藏 匿名内部类在“想要定义一个回调函数却又不想编写 ...

随机推荐

  1. 手写 Promise

    在上一章节中我们了解了 Promise 的一些易错点,在这一章节中,我们会通过手写一个符合 Promise/A+ 规范的 Promise 来深入理解它,并且手写 Promise 也是一道大厂常考题,在 ...

  2. ElasticSearch快速入门

    知识储备 学习ElasticSearch之前可以先了解一下lucene,这里是我整理的一篇关于lucene的笔记(传送门),对搜索框架有兴趣的还可以了解一下另一款企业级搜索应用服务器---solr(传 ...

  3. linux之samba使用

    工作中,很多时候,我导出文件,或者上传文件的时候经常失败,报samba fail,但我并不知道samba是干什么用的,也老是听同事说什么samba没有挂载,但我基本上不知道什么是samba,更不要说什 ...

  4. CAD制图系列之如何画内切圆

    今天我将记录我们如何画一个大圆,里面均匀内切四个小圆 具体步骤如下: 第一步:首先,先画一个十字架,用于作为轴 第二步:以十字架交点为圆心,画一个半径为25的圆 第三步:以中点为坐标画四十五度斜线,方 ...

  5. ROS中3D机器人建模(四)

    一.创建一个7-DOF机械臂机器人 创建一个名为seven_dof_arm.xacro的文件,写入相应的代码,其关节名称如下: bottom_joint shoulder_pan_joint shou ...

  6. 时序数据库 Apache-IoTDB 源码解析之前言(一)

    IoTDB 是一款时序数据库,相关竞品有 Kairosdb,InfluxDB,TimescaleDB等,主要使用场景是在物联网相关行业,如:车联网.风力发电.地铁.飞机监控等等,具体应用案例及公司详情 ...

  7. 使用nginx搭建一个可用的静态资源web服务器

    新建dlib目录,dlib里面放着很多index.html文件 修改conf文件 配置location,/所有的请求,这里一般使用alias,这样url后面的路径和dlib/下面的路径是一一对应的,如 ...

  8. Java的Integer与int互转

    int转Integer ; Integer wrapperi = new Integer(i); Integer转int ); int i = wrapperi.intValue(); JDK1.5以 ...

  9. GetModuleFileNameEx遍历获取64bit程序路径失败的一种解决方法(Win7-64-bit)

    问题: 32位程序在64位系统上调用GetModuleFileNameEx()遍历获取64位进程的全路径失败,得到的路径都为空. 根据官方的说法: For the best results use t ...

  10. 谷歌翻译API

    http://translate.google.cn/translate_a/t?client=t&text=你好&hl=zh-CN&sl=zh-CN&tl=en&am ...