1. 程式人生 > >C++面向物件類的例項題目一

C++面向物件類的例項題目一

在一個程式中,實現如下要求:

(1)建構函式過載

(2)成員函式設定預設引數

(3)有一個友元函式

(4)有一個靜態函式

(5)使用不同的建構函式建立不同物件

code:

#include<iostream>
using namespace std;
class A
{
	public:
		A()
		{
			cout<<"Defalut constructor called."<<endl;//預設建構函式
			count++; 
		}
		A(int i)
		{
			cout<<"constructor1=====>a:"<<i<<endl;	//有一個引數的建構函式 
			a = i;
			count++; 
		}
		friend void show(A &a1);	//定義了一個友元函式 
		static void  show_num()		//定義了一個靜態函式 
		{
			cout<<"number:"<<count<<endl; 
		}
		void set(int i=0)		//定義一個具有預設引數的成員函式 
		{
			a = i;
		} 
		int a;
		static int count;
};
int A::count = 0;	//在類的定義之外初始化靜態成員變數
void show(A &a1)
{
	cout<<"a:"<<a1.a<<endl; 
} 
int main()
{
	A a1,a2(5);
	show(a1);
	show(a2);
	A::show_num();
}

輸出:
Defalut constructor called.
constructor1=====>a:5
a:0
a:5
number:2