学习c++的第六天
学习内容:
- 掌握声明类的方法,类和类的成员的概念以及定义对象的方法;
- 掌握用类和对象编制基于对象的程序;
- 掌握类、类的构造函数和析构函数的定义和使用,理解不同访问属性的成员的访问方式;
- 掌握构造函数和析构函数的执行过程;
- 掌握类的组合使用方法。
- 定义一个复数类,要求含有构造函数、拷贝构造函数和析构函数,并实现复数的加法、减法、乘法和除法等基本四则远算。
遇到的问题:
在整个学习过程中,很容易把C++和C#搞混。但是经过一段时间熟练后,就觉得C++在声明数据成员和方法成员的时候,相对C#来说外观看起来更成体系,整齐划一。而C#就显得比较繁琐。
解决的办法:
就对比着学习,死磕它们。因为C++和C#都是面向对象程序设计语言,所以共通之处还是很多的,但导致了代码书写习惯得改改了。在大同小异的局面中,我们往往只需要记住不一样的地方就可以了。
心得体会:
- 类是对象的抽象
类是抽象的模板,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。
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() { //撒
}
};
- 构造函数的作用:初始化对象的数据成员。
当创建一个对象的时候,编译系统会给对象分配内存空间,并自动调用该类的构造函数,由构造函数完成成员的初始化工作。如果类定义了构造函数,则编译器不生成默认的无参数构造函数。 - 析构函数的作用:与构造函数的作用相反,它是用来销毁对象的。
学习内容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;
}