实验1:
#include<iostream> using namespace std; class square { private: float width,length; public: square(float a,float b) { width=a; length=b; }; //构造函数 float calculate(){return width*length;}; }; int main() { float a,b; cout<<"请输入矩形的长:"; cin>>a; cout<<"请输入矩形的宽:"; cin>>b; square s1(a,b); cout<<"矩形的面积为:"<<s1.calculate()<<endl; return 0; }
实验2:
#include<iostream> using namespace std; class complex { private: float real,imaginary=0; //防止虚部未赋值 public: complex(float r,float i) { real=r; imaginary=i; }; complex(float r){real=r;}; //函数重载 void add(complex &c) { real+=c.real; imaginary+=c.imaginary; }; void show(){cout<<"结果为:"<<real<<" + "<<imaginary<<"i"<<endl;}; }; int main() { complex c1(3,5); complex c2=4.5; c1.add(c2); c1.show(); return 0; }
总结:private部分不易被篡改,与结构体比起来更安全。
其中可以使用函数,功能比结构体更强大。
构造函数在定义一个类时将想赋值的变量进行赋值等操作。