(原)第2章 类

class Fraction{
public:
	Fraction(int n, int d = 1)
		:m_Numerator(n),m_Denominator(d){}
private:
	int m_Numerator;
	int m_Denominator;
};

int main(){
   Fraction frac(8);
   /*調用轉換構造函數*/
   Fraction frac2 = 5;
   /*附識*/
   frac = 5;

   /*c的類型影射*/
   frac = (Fraction)7;
   /*顯示的臨時變量*/
   frac = Fraction(6);

   frac = static_cast
 
 
  
  (6);

}
 
 
class Fraction {
public:
	Fraction(int n,int d):m_number(n),m_Denom(d){
		++ctors;
	}

	Fraction(const Fraction& other)
	:m_number(other.m_number),m_Denom(other.m_Denom){
		++copies;
	}

	Fraction & operator= (const Fraction& other){
		m_number = other.m_number;
		m_Denom = other.m_Denom;
		++assigns;
		return *this; 
	}

	Fraction multiply(Fraction f2){
		return Fraction (m_number * f2.m_number, m_Denom * f2.m_Denom);
	}
	static void report();
private:
	int m_number;
	int m_Denom;
	static int ctors;
	static int copies;
	static int assigns;

};
int Fraction::copies = 0;
int Fraction::ctors = 0;
int Fraction::assigns = 0;

#include 
 
 
  
  
int main(int argc, char *argv[])
{
	using namespace std;
	Fraction twothirds(2,3);
	Fraction threequarters(3,4);

	/*以下の二つはコピー構造関数を利用する*/
	Fraction acopy(twothirds);
	Fraction f4 = threequarters;

	cout << "after declarations /n";
	Fraction::report();
	f4 = twothirds;
	cout << "before multiply /n";

	Fraction::report();
	/*お先にFraction(const Fraction& other)を呼びかける*/
	f4 = twothirds.multiply(threequarters);
	cout << "after multply /n";
	Fraction::report();

	return 0;
}
void Fraction::report(){
	std::cout << "/n assigns" << assigns;
	std::cout << "/n ctors" << ctors;
	std::cout << "/n copies" << copies;
}
 
 

1 )使用结构的主要优势是什么?

2  )指出类与结构之间存在的至少一个不同点。

类与结构的不同点:1,虽然结构与类的类型不一样,可是他们的基类型都是对象。2,虽然结构的初始化也用了new操作,,可结构对象分配在站上,而不是堆上,3,结构是可以没有继承的。4,结构没有默认的构造函数,但是可以添加构造函数,没有析构函数,没有抽象和封装的概念,在结构中初始化实例字段是错误的。

3  )类作用域与块作用域有何不同

4  )描述应该使用友元函数的两种情形。

友元机制允许非成员函数访问一个类的私有数据,友元可以是一个类,也可以是另外一个类的成员函数,还可以是任何一个非成员函数。1种情形是使用工厂方法,还有一种是使用全局操作符函数。

5  )静态数据成员和非静态数据成员相比有什么不同?

6  )静态成员函数和非静态成员函数之间有什么不同?

一个类的静态数据成员也仅仅在程序开始执行之前创建一次,同样在程序终止的时候销毁。静态数据对象不属于某个特定的对象。它是被该类的所有对象共享。

静态成员函数只能访问静态成员,它没有this指针,属于整个类而非类的对象。

7  )把一个函数申明为const有什么实际含义

表明此函数不能改变主对象的状态,也就是this是一个指向const变量的指针。

8  )试解释如果某个类T有一个原形如下的构造函数将会出现什么问题?T::T(T other);

会出现编译错误。

补充:

转换构造函数:可以只用一个(不同类型的)参数进行调用的构造函数。使用关键字explicit将阻止隐式机制使用此构造函数。

class Timer{
public:
    /*其所有成员函数都可以访问到m_elapsed*/
    friend class Clock;
    friend void Time::toString();
    friend ostream& operator <<(ostream& os, const Timer& obj);

private:
long m_elapsed;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的横打

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值