⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 练习.txt

📁 钱能主编 C++程序设计教程(第一版) 该书习题的答案代码
💻 TXT
字号:
12.1 //write the result of the program below
#include <iostream.h>

class MyClass
{
public:
	MyClass();
	MyClass(int);
	~MyClass();
	void Display();
protected:
	int number;
};

MyClass::MyClass()
{
	cout<<"Constructing normally."<<endl;
}
MyClass::MyClass(int m)
{
	number=m;
	cout<<"Constructing with a number: "<<number<<endl;
}
void MyClass::Display()
{
	cout<<"Display a number: "<<number<<endl;
}
MyClass::~MyClass()
{
	cout<<"Destructing."<<endl;
}

void main()
{
	MyClass obj1;
	MyClass obj2(20);

	obj1.Display();
	obj2.Display();
}

12.2
#include <iostream.h>

class Employee
{
public:
Employee::Employee(char* pName="noName",char* pAdd="noAdd",char* pPost="noPost")
:name(pName),address(pAdd),postcode(pPost)
{
	//name=pName;                  //两种初始化方法均可,
	//address=pAdd;                //但一起用就重复了,通不过编译
	//postcode=pPost;
}
	void ChangeName(char* pNewName);
	void Display();
protected:
	char* name;
	char* address;
	char* postcode;
};


void Employee::ChangeName(char* pNewName)
{
	name=pNewName;
	cout<<"the name of employee has been changed."<<endl;
}
void Employee::Display()
{
	cout<<"Name   :"<<name<<endl
		<<"Address:"<<address<<endl
		<<"Post   :"<<postcode<<endl;
}

void main()
{
	Employee a;
	a.Display();
	Employee b("BEYOND","HongKong","800032");  //此处亦可用指针赋值,即Employee b(p1,p2,p3) ,其中的p1,p2,p3须在定义b之前初始化。
	b.Display();
}

12.3(类Name以头文件形式说明,在主文件中以#include "Name.h"说明)
//**********************
//**      Name.h      **
//**********************
#include <iostream.h>

class Name
{
public:
	Name(char* cplName="f_name l_name")
	{
		name=cplName;
	}
	void Disp()
	{
		cout<<name<<endl;
	}
protected:
	char* name;
};

//************************
//**      main.cpp      **
//************************
#include <iostream.h>
#include "Name.h"

class Employee
{
public:
Employee::Employee(char* pName="noName",char* pAdd="noAdd",char* pPost="noPost")
:name(pName),address(pAdd),postcode(pPost)
{
	//name=pName;
	//address=pAdd;
	//postcode=pPost;
}
	void ChangeName(char* pNewName);
	void Display();
protected:
	Name name;
	char* address;
	char* postcode;
};


void Employee::ChangeName(char* pNewName)
{
	name=pNewName;
	cout<<"the name of employee has been changed."<<endl;
}
void Employee::Display()
{
	cout<<"Name   :";
	name.Disp();
	cout<<"Address:"<<address<<endl
		<<"Post   :"<<postcode<<endl;
}

void main()
{
	Employee a;
	a.Display();
	Employee b("BEYOND","HongKong","800032");
	b.Display();
}
12.4
与12.3基本相同,只是把Name和Employee两个类独立成两个头文件,main文件如下:
//************************
//**      main.cpp      **
//************************
#include <iostream.h>
#include "Name.h"
#include "Employee.h"

void main()
{
	Employee em("Mark Brooks","5 West St. Reverse, CA","12290");

	//char buffer[225];
	em.Display();

	em.ChangeName("Richard Voss");
	em.Display();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -