类与对象(凑够五个字)

学习c++的第六天

学习内容:

  1. 掌握声明类的方法,类和类的成员的概念以及定义对象的方法;
  2. 掌握用类和对象编制基于对象的程序;
  3. 掌握类、类的构造函数和析构函数的定义和使用,理解不同访问属性的成员的访问方式;
  4. 掌握构造函数和析构函数的执行过程;
  5. 掌握类的组合使用方法。
  6. 定义一个复数类,要求含有构造函数、拷贝构造函数和析构函数,并实现复数的加法、减法、乘法和除法等基本四则远算。

遇到的问题:

在整个学习过程中,很容易把C++和C#搞混。但是经过一段时间熟练后,就觉得C++在声明数据成员和方法成员的时候,相对C#来说外观看起来更成体系,整齐划一。而C#就显得比较繁琐。

解决的办法:

就对比着学习,死磕它们。因为C++和C#都是面向对象程序设计语言,所以共通之处还是很多的,但导致了代码书写习惯得改改了。在大同小异的局面中,我们往往只需要记住不一样的地方就可以了。

心得体会:

  1. 类是对象的抽象
    是抽象的模板,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。
    eg:
class Human(){

private:
	int age;
	string height;
	string weight;
	string gender;
	string name;
	double id_number;
public:
	Human() {  //构造函数

	}
	~Human() {  //析构函数

	}
	void Eat() { //吃

	}
	void Drink() {  //喝

	}
	void Excretion() {  //拉

	}
	void Urnary() {  //撒

	}
};
  1. 构造函数的作用:初始化对象的数据成员。
    当创建一个对象的时候,编译系统会给对象分配内存空间,并自动调用该类的构造函数,由构造函数完成成员的初始化工作。如果类定义了构造函数,则编译器不生成默认的无参数构造函数。
  2. 析构函数的作用:与构造函数的作用相反,它是用来销毁对象的。

学习内容6的代码

#include<iostream>
#include<string>


using namespace std;

class Plural{

private:
	double realpart; //实部;
	double imaginarypart; //虚部;
public:

	Plural() {

	}
	~Plural() {
		cout << "析构函数被调用!" << endl;
	}
	void Addtion(double a1, double b1, double a2, double b2) { //复数加法;
		realpart = a1 + b1;
		imaginarypart = b1 + b2;
		PrintAddandSub(realpart, imaginarypart,1);
	}
	void Subtraction(double a1, double b1, double a2, double b2) { //复数减法;
		realpart = a1 - b1;
		imaginarypart = b1 - b2;
		PrintAddandSub(realpart, imaginarypart, 2);
	}

	void Division(double a1, double b1, double a2, double b2) { //复数除法;
		PrintMultiandDiv(a1, a2, b1, b2, 3);
	}
	void Multiplication(double a1, double b1, double a2, double b2) { //复数乘法;
		PrintMultiandDiv(a1, a2, b1, b2, 4);
	}

	void PrintAddandSub(double realpart, double imaginarypart, int x) {
		if (x == 1) {
			//加法;
			cout << "加法:" << realpart << "+" << imaginarypart << "i" << endl;
		}
		if (x == 2) {
			//减法;
			cout << "减法:" << realpart << "-" << imaginarypart << "i" << endl;
		}
	
	}
	
	void PrintMultiandDiv(double a1, double b1, double a2, double b2, int x) {

			if (x == 3) {
				//除法;
				cout << "除法:" << (a1 * a2 + b1 * b2) / (a2 * a2 + b2 * b2)
					<< "+" << (a2 * b1 - a1 * b2) / (a2 * a2 + b2 * b2) << "i" << endl;
			}
			if (x == 4) {
				//乘法;
				cout << "乘法:" << a1*a2-b1*b2
					<< "+" << a1*a2+a2*b1 << "i" << endl;
			}
	}
	

};
int main()
{
	double a1, b1;
	double a2, b2;
	cout << "请输入复数1的实部a1和虚部b1:";
	cin >> a1 >> b1;
	cout << "请输入复数2的实部a2和虚部b2:";
	cin >> a2 >> b2;

	Plural z;
	z.Addtion(a1, b1, a2, b2);
	z.Subtraction(a1, b1, a2, b2);
	z.Division(a1, b1, a2, b2);
	z.Multiplication(a1, b1, a2, b2);
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值