一开始的版本
#include<iostream> #include<cmath> #include<cstdlib> using namespace std; class Complex { public: Complex(double newr = 0, double newi = 0);//此处因为题目要求,Complex c1(3,5)和Complex c2 = 4.5,两种定义方式,我发现只写这一行不够 Complex(){ //于是加了一个无参数,同样作用的构造函数Complex,利用了构造函数的重载,这样就可以实现要求的这两行了。 real = 0; imaginary = 0; } Complex(Complex &c1); void add(Complex c1); void show(); double mod(); private: double real; double imaginary; }; //构造函数 Complex::Complex(double newr, double newi) { real = newr; imaginary = newi; } //复制构造函数 Complex::Complex(Complex &c1)
{
real=c1.real;
imaginary = c1.imaginary;
} //复数相加 void Complex::add(Complex c1) { real += c1.real; imaginary += c1.imaginary; } //输出 void Complex::show() { if (imaginary != 0) cout << real << "+" << imaginary << "i" << endl; else cout << real << endl; } //取模 double Complex::mod() { return sqrt(real*real + imaginary * imaginary); } int main() { Complex c1(3,5); Complex c2 = 4.5; Complex c3(c1); Complex c4; //但是这里会出现问题,因为函数的重载无法判断c4是由第一个还是第二个构造函数定义的,所以此处实现不了 c1.add(c2); cout << "c1="; c1.show(); cout << "c2="; c2.show(); cout << "c3="; c3.show(); cout << "c4="; c4.show(); cout << "c1.mod="<<c1.mod()<<endl; system("pause"); return 0; }
然后研究了一下怎么才能写一个构造函数而两种定义方法通用
修改版
#include<iostream> #include<cmath> #include<cstdlib> using namespace std; class Complex { public: Complex(double newr = 0, double newi = 0); Complex(Complex &c1); void add(Complex c1); void show(); double mod(); private: double real; double imaginary; }; //构造函数 Complex::Complex(double newr, double newi) :real(newr), imaginary(newi) {}//利用函数初始化列表 //复制构造函数 Complex::Complex(Complex &c1) : real(c1.real), imaginary(c1.imaginary) {}//利用函数初始化列表 //复数相加 void Complex::add(Complex c1) { real += c1.real; imaginary += c1.imaginary; } //输出 void Complex::show() { if (imaginary != 0) cout << real << "+" << imaginary << "i" << endl; else cout << real << endl; } //取模 double Complex::mod() { return sqrt(real*real + imaginary * imaginary); } int main() { Complex c1(3,5); Complex c2 = 4.5; Complex c3(c1); Complex c4; c1.add(c2); cout << "c1="; c1.show(); cout << "c2="; c2.show(); cout << "c3="; c3.show(); cout << "c4="; c4.show(); cout << "c1.mod="<<c1.mod()<<endl; system("pause"); return 0; }
https://blog.csdn.net/yu132563/article/details/80103887
但是在这篇文章中,函数体内初始化和函数初始化列表应该是相同的作用,并没有什么区别,我也没有搞懂为什么用了初始化列表就可以这么做了,望各位看官解答一下(˘•ω•˘)
----X.Raven