InterviewGuide icon indicating copy to clipboard operation
InterviewGuide copied to clipboard

勘误和解释优化 01-01-02-basic.md

Open YINGHAIDADA opened this issue 1 year ago • 0 comments

勘误:

//语句打印 s4 原来是 s2
printf("s4 age:%d, num:%d\n", s4.age, s4.num);

优化

对于转换构造函数,在原本的举例代码中使用以下举例

...
Student(int r){   //转换构造函数,形参是其他类型变量,且只有一个形参
        this->age = r;
		this->num = 1002;
    };
...
int a = 10;
Student s3(a);

然而这种可能看似像接受不同形参的构造函数,另一种更直观的举例方式可能是类似string s = "demo";, 带有隐式类型转换 以下增加几个例子举例

...
    Student(int r){   //转换构造函数,形参是其他类型变量,且只有一个形参
        this->age = r;
		this->num = 1002;
    };
    Student(const char* name, double score)
    {
        this->age = 0;
        this->num = (int)score;
    }
    Student(double r){   //转换构造函数,形参是其他类型变量,且只有一个形参
        this->age = (int)r * 10;
		this->num = 1003;
    };
...
Student s3 = a; //转换构造函数调用
Student s4(s3);//重载构造函数调用
Student s5("demo",56.45);//重载构造函数调用
Student s6 = 85.63;//转换构造函数调用
float b = 5.2;
Student s7 = b;//转换构造函数调用

/*
s3 age:10, num:1002
s4 age:10, num:1002
s5 age:0, num:56
s6 age:850, num:1003
s7 age:50, num:1003
*/

YINGHAIDADA avatar Mar 13 '24 04:03 YINGHAIDADA