语法规则在代码注释里,对照代码看哦,便于理解,可以直接将代码拷贝到你的IDE或者编辑器里。
#include <iostream>
using namespace std;
class Complex{
private:
double real,imag;
public:
Complex(double r);
Complex(double r, double i);
Complex(Complex c1,Complex c2);
};
Complex::Complex(double r){
cout << "构造函数1执行" << endl;
real = r;
imag = 0;
}
Complex::Complex(double r,double i){
cout << "构造函数2执行" << endl;
real = r;
imag = i;
}
Complex::Complex(Complex c1,Complex c2){
cout << "构造函数3执行" << endl;
real = c1.real + c2.real;
imag = c1.imag + c2.imag;
}
int main()
{
Complex c1(3);
Complex c2(1,2);
Complex c3(c1,c2);
Complex c4 = 7;
return 0;
}
#include <iostream>
using namespace std;
class Complex{
public:
double real,imag;
Complex(double r, double i){
real = r;
imag = i;
cout << "Constructor called" << endl;
}
Complex(const Complex & c){
real = c.real;
imag = c.imag;
cout << "Copy Constructor called" << endl;
}
};
void case1(){
Complex c1(1,1);
Complex c2(c1);
cout << c2.real << "," << c2.imag << endl;
Complex c3 = c1;
cout << c3.real << "," << c3.imag << endl;
}
void Func(Complex a){
cout << a.real << "," << a.imag << endl;
}
void case2(){
Complex b(2,2);
Func(b);
}
Complex Func2(){
Complex b(3,3);
return b;
}
void case3(){
cout << Func2().real << "," << Func2().imag << endl;
}
void note(){
Complex c1(4,4);
Complex c2(6,6);
c2 = c1;
cout << c2.real << "," << c2.imag << endl;
}
int main()
{
case1();
cout<<"\n";
case2();
cout<< "\n";
case3();
cout<< "\n";
note();
return 0;
}
#include <iostream>
using namespace std;
class Complex{
public:
double real,imag;
Complex(double r, double i){
real = r;
imag = i;
cout << "Constructor called" << endl;
}
Complex(int i){
real = i;
imag = 0;
cout << "IntConstructor called" << endl;
}
~Complex(){
cout << "Destrutor called" << endl;
}
};
int main()
{
Complex c1(1.0,1.0);
cout << c1.real << "," << c1.imag << endl;
c1 = 520;
cout << c1.real << "," << c1.imag << endl;
Complex c2 = 12;
cout << c2.real << "," << c2.imag << endl;
return 0;
}
#include <iostream>
using namespace std;
class Complex{
int id;
public:
Complex(int i){
id = i;
cout <<"id=" << id << ",Constructor called" << endl;
}
Complex(const Complex & c){
id = c.id;
cout << "id=" << id << ",Copy Constructor called" << endl;
}
~Complex(){
cout << "id=" << id << ",Destructor called" << endl;
}
void print(){
cout << "id=" << id << endl;
}
};
Complex c1(1);
Complex Func(){
static Complex c2(2);
cout << "\nTemporary Object start\n";
return c2;
}
int main()
{
cout << "main" << endl;
Complex c3(3);
Func().print();
cout << "Temporary Object end\n\n";
{
Complex* c5 = new Complex(5);
delete c5;
}
return 0;
}