C++基础学习教程(五)
这一讲我们集中解说类和他的一些特性.首先我们从自己定义一个有理数类来開始.
在C语言中有一个keyword: struct ,用来创建一个结构体类型.可是在C++中这个关键的含义就不只如此了,以下我们能够看下演示样例:
/// Represent a rational number.
struct rational
{
int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
};
首先认为这个和C语言中看起来是一样的,分子是numerator,分母是denominator,事实上不然,上面那段代码实际上是创建了一个类型,即是一个类型的定义,换言之,就是编译器会记住rational命名了一个类型,仅仅是没有为对象numerator和denominator分配内存,用C++的说法,numerator和denominator是数据成员. 注意花括号后面的分号结束符!!!!
以下为了验证这是一个类型,我们能够创建一个rational的对象,然后使用点(.)操作符訪问成员,例如以下:
/** Using a Class and Its Members */
#include <iostream>
#include <ostream> /// Represent a rational number.
struct rational
{
int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
}; int main()
{
rational pi;
pi.numerator = 355;
pi.denominator = 113;
std::cout << "pi is about " << pi.numerator << "/" << pi.denominator << '\n';
}
执行结果例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Vvb2w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
如今能够看出这确实是一个类型,那么如今我们就进一步扩展这个类型,首先,添加一个分数自己主动约分的功能.rational类型已经有了数据成员,我们如今为其编写一个约分的函数成员,例如以下:
/** @file ReduceduceRational.cpp */
/** Adding the reduce Member Function */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ostream> /// Compute the greatest common divisor of two integers, using Euclid’s algorithm.
int gcd(int n, int m)
{
n = abs(n);
while (m != 0) {
int tmp(n % m);
n = m;
m = tmp;
}
return n;
} /// Represent a rational number.
struct rational
{
/// Reduce the numerator and denominator by their GCD.
void reduce()
{
assert(denominator != 0);
int div(gcd(numerator, denominator));
numerator = numerator / div;
denominator = denominator / div;
} int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
}; int main()
{
rational pi;
pi.numerator = 1420;
pi.denominator = 452;
pi.reduce();
std::cout << "pi is about " << pi.numerator << "/" << pi.denominator << '\n';
}
运行结果例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Vvb2w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
注意reduce看起来是一个普通的函数,可是出如今rational的类型定义内.并要注意在reduce内部调用rational数据成员的方式.而当调用reduce函数时候,点操作符的左边必须是一个对象,当reduce()函数指向一个数据成员时,该数据成员从左操作数获取.
上面代码中gcd函数是利用欧几里得算法就最大公约数,是一个自由函数,不论什么的两个整数都能够作为參数调用它,他作为自由函数和rational类型没有不论什么的关系,不过用作计算最大公约数,全然没有改动rational()的数据成员.
而在上面的代码中我们定义了一个reduce()成员函数,如今我们继续扩展rational类型,添加一个assign()成员函数,并让assign()成员函数调用reduce()函数.即是在类型定义内部能够定义多个函数,而且函数之间能够调用.代码例如以下:
/** @file ReduceAssignRational.cpp */
/** Adding the assign Member Function */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ostream>
/// Compute the greatest common divisor of two integers, using Euclid’s algorithm.
int gcd(int n, int m)
{
n = abs(n);
while (m != 0) {
int tmp(n % m);
n = m;
m = tmp;
}
return n;
} /// Represent a rational number.
struct rational
{
/// Assign a numerator and a denominator, then reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
void assign(int num, int den)
{
numerator = num;
denominator = den;
reduce();
} /// Reduce the numerator and denominator by their GCD.
void reduce()
{
assert(denominator != 0);
int div(gcd(numerator, denominator));
numerator = numerator / div;
denominator = denominator / div;
} int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
}; int main()
{
rational pi;
pi.assign(1420, 452);
std::cout << "pi is about " << pi.numerator << "/" << pi.denominator << '\n';
}
在上面的代码中,assign()函数调用了reduce()函数,可是assign()函数的定义早于reduce()函数,这里我们有这种规则----编译器在使用一个名字前必须看到该名字的至少一个声明,新类型的成员能够调用其它成员,而不必考虑在类型内的声明顺序.在其它情况下,声明必须早于调用.
同一时候我们也能够看出,在上面创建rational实例对象的时候,我们要么是直接给数据成员赋值,要么调用当中的一个assign()函数赋值,而学习过其它高级语言的应该都知道我们应该通过构造函数来初始化一个类型的实例,那么如今我们就把rational类型加入构造函数,(构造器),代码例如以下:
/** @file ConstructRational.cpp */
/** Adding the Ability to Initialize a rational Object */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ostream> /// Compute the greatest common divisor of two integers, using Euclid’s algorithm.
int gcd(int n, int m)
{
n = abs(n);
while (m != 0) {
int tmp(n % m);
n = m;
m = tmp;
}
return n;
} /// Represent a rational number.
struct rational
{
/// Construct a rational object, given a numerator and a denominator.
/// Always reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
rational(int num, int den)
: numerator(num), denominator(den)
{
reduce();
} /// Assign a numerator and a denominator, then reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
void assign(int num, int den)
{
numerator = num;
denominator = den;
reduce();
} /// Reduce the numerator and denominator by their GCD.
void reduce()
{
assert(denominator != 0);
int div(gcd(numerator, denominator));
numerator = numerator / div;
denominator = denominator / div;
} int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
}; int main()
{
rational pi(1420, 452);
std::cout << "pi is about " << pi.numerator << "/" << pi.denominator << '\n';
}
当中的构造函数就是
运行结果例如以下:
对上面的构造函数分析。能够知道构造函数的形式和要求为:
- l 函数名称必须为类型名称
- l 函数能够有參数或者无參数(按需而定)
- l 函数參数(非空)后有一个冒号(:)后面是相应的參数初始化相应的数据成员。
如今我们继续扩展这个rational类型,上面的代码都是默觉得分母为正,分子可为负,如今我们要使可以初始化的时候传递负数的分母,这就要求我们对分子分母同一时候取反,这样可以保证分母依旧为正,而数值不变.部分代码例如以下:
/// Reduce the numerator and denominator by their GCD.
void reduce()
{
assert(denominator != 0);
if (denominator < 0) // if denominator < 0
{
denominator = -denominator;
numerator = -numerator;
}
int div(gcd(numerator, denominator));
numerator = numerator / div;
denominator = denominator / div;
}
构造函数是我们接触的最新的函数类型,他相同的能够被重载,重载构造函数的代码例如以下:
/** Constructing a Rational Object from an Integer */
rational(int num)
: numerator(num), denominator(1)
{}
这个是一个參数的构造函数,默认分母为1.并且显然不须要调用reduce函数.
我们既然创造了一个新的数据类型,那么就也须要创造这个数据类型的操作行为,就是重载操作符,使他也可以实现四则运算和大小比較等.以下就是运算符重载的代码:
/** @file OverrideOperator.cpp */
/** Overloading the Equality Operator */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ostream> using namespace std; /// Compute the greatest common divisor of two integers, using Euclid’s algorithm.
int gcd(int n, int m)
{
n = abs(n);
while (m != 0) {
int tmp(n % m);
n = m;
m = tmp;
}
return n;
} /// Represent a rational number.
struct rational
{
/// Construct a rational object, given a numerator and a denominator.
/// Always reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
rational(int num, int den)
: numerator(num), denominator(den)
{
reduce();
}
rational(int num)
: numerator(num), denominator(1)
{} /// Assign a numerator and a denominator, then reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
void assign(int num, int den)
{
numerator = num;
denominator = den;
reduce();
} /// Reduce the numerator and denominator by their GCD.
void reduce()
{
assert(denominator != 0);
if (denominator < 0)
{
denominator = -denominator;
numerator = -numerator;
}
int div(gcd(numerator, denominator));
numerator = numerator / div;
denominator = denominator / div;
} int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
}; /// Compare two rational numbers for equality.
/// @pre @p a and @p b are reduced to normal form
bool operator==(rational const& a, rational const& b)
{
return a.numerator == b.numerator && a.denominator == b.denominator; // ==
} /// Compare two rational numbers for inequality.
/// @pre @p a and @p b are reduced to normal form
inline bool operator!=(rational const& a, rational const& b)
{
return ! (a == b); // !=
} /// Compare two rational numbers for less-than.
bool operator<(rational const& a, rational const& b)
{
return a.numerator * b.denominator < b.numerator * a.denominator; // <
} /// Compare two rational numbers for less-than-or-equal.
inline bool operator<=(rational const& a, rational const& b)
{
return ! (b < a); // <=
} /// Compare two rational numbers for greater-than.
inline bool operator>(rational const& a, rational const& b)
{
return b < a; // >
} /// Compare two rational numbers for greater-than-or-equal.
inline bool operator>=(rational const& a, rational const& b)
{
return ! (b > a); // >=
} /** Addition Operator for the rational Type */
rational operator+(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator + rhs.numerator * lhs.denominator,
lhs.denominator * rhs.denominator); // +
} rational operator-(rational const& r)
{
return rational(-r.numerator, r.denominator); // -
} /** Arithmetic Operators for the rational Type */
rational operator-(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator - rhs.numerator * lhs.denominator,
lhs.denominator * rhs.denominator); // -
} rational operator*(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.numerator,
lhs.denominator * rhs.denominator); // *
} rational operator/(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator,
lhs.denominator * rhs.numerator); // /
} void print(rational const & result)
{
cout << result.numerator << '/' << result.denominator << '\n' ;
} int main()
{
rational rat_a (1,9);
rational rat_b (2,7);
rational rat_c (3,8);
rational rat_d (4,7);
rational result_a(rat_a + rat_b);
rational result_b(rat_a / rat_b);
rational result_c(rat_c - rat_a); // the result < 0
rational result_d(- rat_d); // override -
bool result_bool_a (rat_a > rat_d);
bool result_bool_b (rat_a <= rat_c); print(rat_a);
print(rat_b);
print(rat_c);
print(rat_d);
print(result_a);
print(result_b);
print(result_c);
print(result_d);
cout << result_bool_a << '\n';
cout << result_bool_b << '\n'; rational result(3 * rational(1, 3));
cout << result.numerator << '/' << result.denominator << '\n';
}
上面就是全部的运算符重载的函数,当中的构造函数有两个,一个是双參数一个是单參数,所以在上面的main函数中最后两行代码才干够通过编译并成功运行,由于里面的整数3被自己主动转换为rational类型的.
相同一些数学函数也是一样,比方求绝对值的函数重载代码段例如以下:
/** Computing the Absolute Value of a Rational Number */
rational absval(rational const& r)
{
return rational(abs(r.numerator), r.denominator);
}
当然这个函数非常easy重载,可是假设是涉及到浮点数的怎么办呢?比方sqrt开开方函数.而假设编译器知道怎样将有理数rational转换为浮点数的话,就能够将rational实參传递给已有的浮点函数,无需再做进一步的工作.可是要用那种类型的浮点数,这个因为需求不同而变化,所以我们要放弃自己主动转换浮点类型,取而代之的是使用三个显式的计算有理数的浮点值的函数.代码段例如以下(须要使用static_cast将分子和分母转为须要的浮点类型)
/** Converting to Floating-point Types */
struct rational
{
float as_float()
{
return static_cast<float>(numerator) / denominator;
} double as_double()
{
return numerator / static_cast<double>(denominator);
} long double as_long_double()
{
return static_cast<long double>(numerator) /
static_cast<long double>(denominator);
}
};
眼下为止的完整版的代码例如以下:
/** @file OverrideOperator.cpp */
/** Overloading the Equality Operator */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ostream> using namespace std; /// Compute the greatest common divisor of two integers, using Euclid’s algorithm.
int gcd(int n, int m)
{
n = abs(n);
while (m != 0) {
int tmp(n % m);
n = m;
m = tmp;
}
return n;
} /// Represent a rational number.
struct rational
{
/// Construct a rational object, given a numerator and a denominator.
/// Always reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
rational(int num, int den)
: numerator(num), denominator(den)
{
reduce();
}
rational(int num)
: numerator(num), denominator(1)
{} /// Assign a numerator and a denominator, then reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
void assign(int num, int den)
{
numerator = num;
denominator = den;
reduce();
} /// Reduce the numerator and denominator by their GCD.
void reduce()
{
assert(denominator != 0);
if (denominator < 0)
{
denominator = -denominator;
numerator = -numerator;
}
int div(gcd(numerator, denominator));
numerator = numerator / div;
denominator = denominator / div;
} /** Converting to Floating-point Types */
float as_float()
{
return static_cast<float>(numerator) / denominator;
} double as_double()
{
return numerator / static_cast<double>(denominator);
} long double as_long_double()
{
return static_cast<long double>(numerator) /
static_cast<long double>(denominator);
} int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
}; /// Compare two rational numbers for equality.
/// @pre @p a and @p b are reduced to normal form
bool operator==(rational const& a, rational const& b)
{
return a.numerator == b.numerator && a.denominator == b.denominator; // ==
} /// Compare two rational numbers for inequality.
/// @pre @p a and @p b are reduced to normal form
inline bool operator!=(rational const& a, rational const& b)
{
return ! (a == b); // !=
} /// Compare two rational numbers for less-than.
bool operator<(rational const& a, rational const& b)
{
return a.numerator * b.denominator < b.numerator * a.denominator; // <
} /// Compare two rational numbers for less-than-or-equal.
inline bool operator<=(rational const& a, rational const& b)
{
return ! (b < a); // <=
} /// Compare two rational numbers for greater-than.
inline bool operator>(rational const& a, rational const& b)
{
return b < a; // >
} /// Compare two rational numbers for greater-than-or-equal.
inline bool operator>=(rational const& a, rational const& b)
{
return ! (b > a); // >=
} /** Addition Operator for the rational Type */
rational operator+(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator + rhs.numerator * lhs.denominator,
lhs.denominator * rhs.denominator); // +
} rational operator-(rational const& r)
{
return rational(-r.numerator, r.denominator); // -
} /** Arithmetic Operators for the rational Type */
rational operator-(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator - rhs.numerator * lhs.denominator,
lhs.denominator * rhs.denominator); // -
} rational operator*(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.numerator,
lhs.denominator * rhs.denominator); // *
} rational operator/(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator,
lhs.denominator * rhs.numerator); // /
} void print(rational const & result)
{
cout << result.numerator << '/' << result.denominator << '\n' ;
} int main()
{
rational rat_a (1,9);
rational rat_b (2,7);
rational rat_c (3,8);
rational rat_d (4,7);
rational result_a(rat_a + rat_b);
rational result_b(rat_a / rat_b);
rational result_c(rat_c - rat_a); // the result < 0
rational result_d(- rat_d); // override -
bool result_bool_a (rat_a > rat_d);
bool result_bool_b (rat_a <= rat_c); print(rat_a);
print(rat_b);
print(rat_c);
print(rat_d);
print(result_a);
print(result_b);
print(result_c);
print(result_d);
cout << result_bool_a << '\n';
cout << result_bool_b << '\n'; rational result(3 * rational(1, 3));
cout << result.numerator << '/' << result.denominator << '\n'; rational pi(355, 113);
rational bmi(90*100*100, 180*180); // Body-mass index of 90 kg, 180 cm
double circumference(0), radius(10); circumference = 2 * pi.as_double() * radius;
cout << "circumference of circle with radius " << radius << " is about "
<< circumference << '\n';
cout << "bmi = " << bmi.as_float() << '\n'; }
运行结果例如以下:
如今我们的rational类型差点儿已经和int内置类型差点儿相同了,可是另一个功能有待实现,那就是输入输出,上面的输出输入是通过专门的函数实现的,而不能直接向内置数据类型的输入输出那样,所以我们须要重载I/O操作符.
在C++中,输入出符一样能够被重载.对于输入操作符,及时提取器(>>)。他的第一个參数为std::istream& 。必须是很了引用。以便在函数中改动流对象。而第二个參数由于要存储输入值,也必须是很量引用。
返回值通常就是他的第一个參数,类型std::istream& ,以便在同一个表达式中连接多个输入操作符。
函数体完毕输入的提取解析和翻译工作。虽然完好的错误处理眼下还难以实现,可是假如主要的错误处理还是非常easy的。
每一个流用一个状态掩码跟踪错误,例如以下:
当输入非法时,输入函数在流的错误状态设置failbit位。
调用者通过状态測试字检測流状态。若状态字设置了failbit则说明流出现了错误。
以下定义rational类型格式,一方面应该易于阅读和书写。同一时候也应该易于高速读取和解析,并且要让输入格式可以识别输出格式以及其它格式。
定义格式为整数、斜线(/),整数,且各个元素之间可插入随意的空格,除非设置流的状态位为禁用。若一个整数后没有斜线,则该数即为结果(分母为一)。成员函数unget()使输入操作符退回多读入的字符。
整数操作符与此类似:尽量多读入字符直到读入的字符不属于该整数为止,然后回退最后一个字符。
输入操作符的重载代码例如以下:
/** @file OverrideIO.cpp */
/** Input Operator */
#include <ios> // declares failbit, etc.
#include <istream> // declares std::istream and the necessary >> operators std::istream& operator>>(std::istream& in, rational& rat)
{
int n(0), d(0);
char sep('\0');
if (not (in >> n >> sep))
// Error reading the numerator or the separator character.
in.setstate(std::cin.failbit);
else if (sep != '/')
{
// Read numerator successfully, but it is not followed by /.
// Push sep back into the input stream, so the next input operation
// will read it.
in.unget();
rat.assign(n, 1);
}
else if (in >> d)
// Successfully read numerator, separator, and denominator.
rat.assign(n, d);
else
// Error reading denominator.
in.setstate(std::cin.failbit); return in;
}
使用输出操作符时。面对很多的棘手的格式化问题,包含字符宽度设置和对齐方式选择,按需插入填充字符,以及仅重设字符宽度而不改变其它格式设置等。
编写复杂的输出操作符的关键在于利用暂时输入流将文字存在string类型的字符串中。Std::osringstream类型在<sstream>中声明,使用方式与cout等输出流同样。操作完毕后,使用成员函数str()返回生成的string类型字符串。
在rational的输入操作符中,创建一个ostringstream,并写入分子。分隔符,分母。然后将生成的字符串写入实际的输出流中,并让输出流处理宽度,对齐和填充。
假设将分子分隔符,分母直接写入输出中。则宽度设置仅仅能应用于分子。使对齐格式出错。和输入符一样,输出操作符返回也是第一个參数。类型std::ostream& ,第二个參数能够按值传递或者传入常量引用。代码例如以下:
/** @file Output.cpp */
/** Output Operator */
#include <ostream> // declares the necessary << operators
#include <sstream> // declares the std::ostringstream type std::ostream& operator<<(std::ostream& out, rational const& rat)
{
std::ostringstream tmp;
tmp << rat.numerator;
if (rat.denominator != 1)
tmp << '/' << rat.denominator;
out << tmp.str(); return out;
}
以下就是检測I/O错误的解说:
首先上文说过输入输出流有几个标志位。程序通过检查和设置标志位来測试错误与否。
输入循环在正常情况下会处理输入流的所有数据,直到到达输入流尾端时设置eofbit。此时fail()仍然返回false表明输入流状态正常。因此输入继续下一轮循环。但这一轮中再无数据可读,因此设置failbit并返回错误。循环条件由于false而退出。
当流中包括非法输入。。比如在要读取一个整数的时候却都到了非数字字符。或者出现了硬件错误时候,循环会退出。首先调用bad()成员函数检測硬件错误,返回true则退出,其次eof()成员函数用来检測是否到达文件尾,仅当eofbit被设置返回true。
若bad() eof()同一时候为false且fail()为true。则表明流中含有非法输入。然后程序按需处理。
能够调用clear函数清除错误状态,跳过后进行下一次读取。
代码例如以下,:
/// Tests for failbit only
bool iofailure(istream& in)
{
return in.fail() && !(in.bad());
}
// test for istream
bool infoistream(istream & in)
{
return !(in.bad()) && !(in.eof()) && in.fail()
}
完毕rational类型的最后一步是完好操作符函数和构造函数,首先是赋值操作符的重载,示比例如以下:
/** First Version of the Assignment Operator */
struct rational
{
rational& operator=(rational const& rhs)
{
numerator = rhs.numerator;
denominator = rhs.denominator;
return *this;
}
};
第二种实现例如以下:
/** Assignment Operator with Explicit Use of this-> */
struct rational
{
rational& operator=(rational const& that)
{
this->numerator = that.numerator;
this->denominator = that.denominator;
return *this;
}
};
上面仅仅是赋值操作符的參数为rational类型的实现,參数也能够是整数,对赋值操作符再次重载例如以下:
/** Assignment of an Integer to a Rational */
struct rational
{
rational& operator=(int num)
{
this->numerator = num;
this->denominator = 1;
return *this;
}
};
编译器会自己主动生成构造函数.特别的是,复制构造函数会将一个rational对象的全部对象成员拷贝到还有一个rational对象.仅仅要声明一个按值传递的rational实參,编译器就调用复制构造函数将实參拷贝到形參,或者定义一个rational变量且用还有一个rational值初始化时,编译器也会通过复制构造函数生成该变量.和赋值操作符一样,编译器默认实现版本号和我们的须要的版本号一样,因此不是必需再次手动编写复制构造函数.
构造函数一样,必需要编写自己实现的不同的參数的重载版本号的构造函数,才干避免编译器自己主动生成可能不符合的默认构造函数.完整版的构造函数例如以下:
/** Overloaded Constructors for rational */
struct rational
{
rational()
: numerator(0), denominator(1)
{/*empty*/} rational(int num)
: numerator(num), denominator(1)
{/*empty*/} rational(int num, int den)
: numerator(num), denominator(den)
{
reduce();
}
};
如今为止,对rational类型的定义大概完毕了,如今贴一下眼下为止的完整版的代码,以及測试执行结果:
/** @file OverrideOperator.cpp */
/** Overloading the Equality Operator */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ostream>
#include <sstream> using namespace std; /// Compute the greatest common divisor of two integers, using Euclids algorithm.
int gcd(int n, int m)
{
n = abs(n);
while (m != 0)
{
int tmp(n % m);
n = m;
m = tmp;
}
return n;
} /// Represent a rational number.
struct rational
{
/// Construct a rational object, given a numerator and a denominator.
/// Always reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
// ˫
rational(int num, int den)
: numerator(num), denominator(den)
{
reduce();
}
// Ί
rational(int num)
: numerator(num), denominator(1)
{}
// ΞΊ
rational()
: numerator(0), denominator(1)
{/*empty*/}
// ㊽Ί
rational(double r)
: numerator(static_cast<int>(r * 10000)), denominator(10000)
{
reduce();
}
/// Assign a numerator and a denominator, then reduce to normal form.
/// @param num numerator
/// @param den denominator
/// @pre denominator > 0
void assign(int num, int den)
{
numerator = num;
denominator = den;
reduce();
} rational& operator=(int num)
{
this->numerator = num;
this->denominator = 1;
return *this;
} /// Reduce the numerator and denominator by their GCD.
void reduce()
{
assert(denominator != 0);
if (denominator < 0)
{
denominator = -denominator;
numerator = -numerator;
}
int div(gcd(numerator, denominator));
numerator = numerator / div;
denominator = denominator / div;
} /** Converting to Floating-point Types */
float as_float()
{
return static_cast<float>(numerator) / denominator;
} double as_double()
{
return numerator / static_cast<double>(denominator);
} long double as_long_double()
{
return static_cast<long double>(numerator) /
static_cast<long double>(denominator);
} int numerator; ///< numerator gets the sign of the rational value
int denominator; ///< denominator is always positive
}; /// Compare two rational numbers for equality.
/// @pre @p a and @p b are reduced to normal form
bool operator==(rational const& a, rational const& b)
{
return a.numerator == b.numerator && a.denominator == b.denominator; // ==
} /// Compare two rational numbers for inequality.
/// @pre @p a and @p b are reduced to normal form
inline bool operator!=(rational const& a, rational const& b)
{
return ! (a == b); // !=
} /// Compare two rational numbers for less-than.
bool operator<(rational const& a, rational const& b)
{
return a.numerator * b.denominator < b.numerator * a.denominator; // <
} /// Compare two rational numbers for less-than-or-equal.
inline bool operator<=(rational const& a, rational const& b)
{
return ! (b < a); // <=
} /// Compare two rational numbers for greater-than.
inline bool operator>(rational const& a, rational const& b)
{
return b < a; // >
} /// Compare two rational numbers for greater-than-or-equal.
inline bool operator>=(rational const& a, rational const& b)
{
return ! (b > a); // >=
} /** Addition Operator for the rational Type */
rational operator+(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator + rhs.numerator * lhs.denominator,
lhs.denominator * rhs.denominator); // +
} rational operator-(rational const& r)
{
return rational(-r.numerator, r.denominator); // -
} /** Arithmetic Operators for the rational Type */
rational operator-(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator - rhs.numerator * lhs.denominator,
lhs.denominator * rhs.denominator); // -
} rational operator*(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.numerator,
lhs.denominator * rhs.denominator); // *
} rational operator/(rational const& lhs, rational const& rhs)
{
return rational(lhs.numerator * rhs.denominator,
lhs.denominator * rhs.numerator); // /
}
/** Input and output operators for the rational Type */
istream& operator>>(std::istream& in, rational& rat)
{
int n(0), d(0);
char sep('\0');
if ( !(in >> n >> sep)) // read integer and separator from istream
// Error reading the numerator or the separator character.
in.setstate(std::cin.failbit); // if con`t read them , return failbit, and exit or print tips
else if (sep != '/')
{
// Read numerator successfully, but it is not followed by /.
// Push sep back into the input stream, so the next input operation
// will read it.
in.unget(); // only one integer ,no separator
rat.assign(n, 1);
}
else if (in >> d) // separator is /
// Successfully read numerator, separator, and denominator.
rat.assign(n, d); // assign the rantional
else
// Error reading denominator.
in.setstate(std::cin.failbit); // read fail return in;
} ostream& operator<<(std::ostream& out, rational const& rat)
{
std::ostringstream tmp;
tmp << rat.numerator;
if (rat.denominator != 1)
tmp << '/' << rat.denominator;
out << tmp.str(); return out;
} /// Tests for failbit only
bool iofailure(istream& in)
{
return in.fail() && !(in.bad());
} // test for istream
bool infoistream(istream & in)
{
return !(in.bad()) && !(in.eof()) && in.fail();
} void print(rational const & result)
{
cout << result.numerator << '/' << result.denominator << '\n' ;
} int main()
{
rational rat_a (1,9);
rational rat_b (2,7);
rational rat_c (3,8);
rational rat_d (4,7);
rational result_a(rat_a + rat_b);
rational result_b(rat_a / rat_b);
rational result_c(rat_c - rat_a); // the result < 0
rational result_d(- rat_d); // override -
bool result_bool_a (rat_a > rat_d);
bool result_bool_b (rat_a <= rat_c); print(rat_a);
print(rat_b);
print(rat_c);
print(rat_d);
print(result_a);
print(result_b);
print(result_c);
print(result_d);
cout << result_bool_a << '\n';
cout << result_bool_b << '\n'; rational result(3 * rational(1, 3));
cout << result.numerator << '/' << result.denominator << '\n'; rational pi(355, 113);
rational bmi(90*100*100, 180*180); // Body-mass index of 90 kg, 180 cm
double circumference(0), radius(10); circumference = 2 * pi.as_double() * radius;
cout << "circumference of circle with radius " << radius << " is about "
<< circumference << '\n';
cout << "bmi = " << bmi.as_float() << '\n'; // cout << "Test for I/O operator !" << endl;
// Ԭʽ
//cout << "ʤȫʽז,rational Ѝ" rational inte(12);
rational dou(123.2);
rational z(12,213);
//cout << rational r() << endl;
cout << inte << endl;
cout << dou << endl;
cout << z << endl;
/*
while (cin)
{
if (cin >> r)
// Read succeeded, so no error state is set in the stream.
cout << r << '\n';
else if (iofailure(cin))
{
// Only failbit is set, meaning invalid input. Clear the error state,
// and then skip the rest of the input line.
cout << "δ֪펳,ǫ̐ʤȫ!" << endl;
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
}
else if (infoistream(cin))
{
cout << "Error input " << endl;
}
} if (cin.bad())
cerr << "Unrecoverable input error\n";
*/
}
结果例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Vvb2w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
如今我们就能够继续深入的学习与类相关的编写了.
C++基础学习教程(五)的更多相关文章
- C++基础 学习笔记五:重载之运算符重载
C++基础 学习笔记五:重载之运算符重载 什么是运算符重载 用同一个运算符完成不同的功能即同一个运算符可以有不同的功能的方法叫做运算符重载.运算符重载是静态多态性的体现. 运算符重载的规则 重载公式 ...
- redis学习教程五《管道、分区》
redis学习教程五<管道.分区> 一:管道 Redis是一个TCP服务器,支持请求/响应协议. 在Redis中,请求通过以下步骤完成: 客户端向服务器发送查询,并从套接字读取,通常以阻 ...
- salesforce 零基础学习(五十二)Trigger使用篇(二)
第十七篇的Trigger用法为通过Handler方式实现Trigger的封装,此种好处是一个Handler对应一个sObject,使本该在Trigger中写的代码分到Handler中,代码更加清晰. ...
- salesforce lightning零基础学习(十五) 公用组件之 获取表字段的Picklist(多语言)
此篇参考:salesforce 零基础学习(六十二)获取sObject中类型为Picklist的field values(含record type) 我们在lightning中在前台会经常碰到获取pi ...
- java基础学习笔记五(抽象类)
java基础学习总结——抽象类 抽象类介绍
- C++基础学习教程(一)
開始自己的C++复习进阶之路. 声明: 这次写的博文纯当是一个回想复习的教程.一些非常基础的知识将不再出现.或者一掠而过,这次的主要风格就是演示样例代码非常多~~~ 全部代码在Ubuntu 14.04 ...
- Java基础学习笔记(五) - 常用的API
API介绍 概念:API 即应用编程程序接口.Java API是JDK中提供给我们使用的类说明文档,这些类将底层的代码实现封装.无需关心这些类是如何实现,只需要学习如何使用. 使用:通过API找到需要 ...
- spring boot基础学习教程
Spring boot 标签(空格分隔): springboot HelloWorld 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新 ...
- C++基础学习教程(八)
转载请注明出处:http://blog.csdn.net/suool/article/details/38300117 引入 在进行下一步的学习之前,我们须要厘清几个概念. RAII 首先介绍一个编程 ...
随机推荐
- Vue 2.0学习(七)方法与事件
基本用法 以监听一个按钮的点击事件为例,设计一个计数器,每次点击都加1: <div id = "app"> 点击次数:{{ counter }} <button ...
- Vue 2.0学习(四)计算属性
{{}}模板内的表达式常用于简单的运算,当运算过长或逻辑复杂时,会难以维护. <div> {{ text.split(',').reverse().join('') }} </div ...
- Python正则模块
re模块 import re # match # 从头开始匹配, 只匹配一次,就结束 a = re.match('\d+', '54:58天5488:8451') # 默认就是0个群组 print(a ...
- BZOJ1019 汉诺塔
定义f[i][j]为将i柱上的j个盘挪走(按优先级)的步数 p[i][j]为将i柱上的j个盘按优先级最先挪至何处 首先考虑一定p[i][j]!=i 设初始为a柱,p[i][j-1]为b柱 考虑两种情况 ...
- 如何使用Eclipse插件—Easy Explorer
Easy Explorer是一个Eclipse插件,主要用于快速浏览项目文件的目录,实用性比较强. 使用方法如下: 1.下载Easy Explorer,从此处下载EasyExplorer:http:/ ...
- Eclipse下使用Stanford CoreNLP的方法
源码下载地址:CoreNLP官网. 目前release的CoreNLP version 3.5.0版本仅支持java-1.8及以上版本,因此有时需要为Eclipse添加jdk-1.8配置,配置方法如下 ...
- 【8.20校内测试】【DP】【二分+贪心】
一开始想的贪心,可是发现贪心的问题太多了啊!只能保证当前最优,全局完全无法考虑. 所以正解是dp.预处理出前缀和,枚举每个区间,在每个点记录$now[i]$表示以$i$这个塔结尾的塔组目前的高度.$d ...
- bzoj 1503: [NOI2004]郁闷的出纳员 -- 权值线段树
1503: [NOI2004]郁闷的出纳员 Time Limit: 5 Sec Memory Limit: 64 MB Description OIER公司是一家大型专业化软件公司,有着数以万计的员 ...
- 思科DCHP解决方案
DHCP功能平时用的不算少,而且本人的几乎所有的DHCP功能都是在交换机上实现的,虽然也可以通过PC实现,而且PC的DHCP Server功能还更完善,比如可以不受DHCP作用域的限制.IP分配情况直 ...
- 引用计数的cocos2dx对象内存管理和直接new/delete box2d对象内存管理冲突的解决方法
转载请注明: http://blog.csdn.net/herm_lib/article/details/9316601 项目中用到了cocos2dx和box2d,cocos2dx的内存是基于引用计数 ...