《C++Primer PLus 第五版》读书笔记3
包含对象成员的类
valarray类是由头文件valarray支持的。顾名思义,这个类用于处理数值,他支持诸如将数组中的所有元素的值想家以及在数组中找出最大和最小的值等操作。valarray被定义为一个模板类,以便能够处理不同的数据类型。
一个Student类----一个getline导致构造函数递归的类
[cpp]
// readBook2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "valarray"
#include "string"
class CStudent
{
public:
typedef std::valarray<double> ArrayDb;
CStudent() : sz_Name( "Null Student" ), m_ArrScores()
{
}
CStudent( const string& name ) : sz_Name( name ), m_ArrScores()
{
}
explicit CStudent( int n ) : sz_Name( "Nully" ), m_ArrScores( n )
{
}
CStudent( const string& name, int n ) : sz_Name( name ), m_ArrScores( n )
{
}
CStudent( const string& name, const ArrayDb& a ) : sz_Name( name ), m_ArrScores( a )
{
}
CStudent( const char* name, const double* pd, int n ) : sz_Name( name ), m_ArrScores( pd, n )
{
}
double Average() const
{
if ( m_ArrScores.size() > 0 )
{
return ( m_ArrScores.sum() / m_ArrScores.size() );
}
else
{
return 0;
}
}
const string& GetName() const
{
return sz_Name;
}
double& operator[]( int i)
{
return m_ArrScores[ i ];
}
double operator[]( int i ) const
{
return m_ArrScores[ i ];
}
ostream& CStudent::arr_out( ostream& os ) const
{
int i;
int lim = m_ArrScores.size();
if ( lim > 0 )
{
for ( i = 0; i < lim; i++ )
{
os << m_ArrScores[ i ] << " ";
if ( 4 == i % 5 )
{
os << endl;
}
}
if ( 0 != i % 5 )
{
os << endl;
}
}
else
{
os << "empty array";
}
return os;
}
friend istream& operator >>( istream& is, CStudent& stu );
friend istream& operator <<( istream& os, const CStudent& stu );
friend istream& getline( istream& is, const CStudent& stu );
~CStudent(){};
private:
string sz_Name;
ArrayDb m_ArrScores;
};
istream& operator >>( istream& is, CStudent& stu )
{
is >> stu.sz_Name;
return is;
}
ostream& operator <<( ostream& os, const CStudent& stu )
{
os << "this student name is:" << stu.GetName() << endl;
os << "this student scores is:" << endl;
stu.arr_out( os );
return os;
}
istream& getline( istream& is, const CStudent& stu )
{
getline( is, stu.sz_Name );
return is;
}
const int puplis = 3;
const int quizzes = 5;
void set( CStudent& sa, int n );
int _tmain(int argc, _TCHAR* argv[])
{
CStudent ada[ puplis ] = { CStudent( quizzes ), CStudent( quizzes ), CStudent( quizzes ) };
int i;
for ( i = 0; i < puplis; ++i )
{
set( ada[ i ], quizzes );
}
cout << "\nStudent List:" << endl;
for ( i = 0; i < puplis; ++i )
{
cout << ada[ i ].GetName() << endl;
}
cout << "\nResults:" << endl;
for ( i = 0; i < puplis; i++ )
{
cout << endl << ada[ i ];
cout << "average" << ada[ i ].Average() << endl;
}
cou
补充:软件开发 , C++ ,