InterviewGuide icon indicating copy to clipboard operation
InterviewGuide copied to clipboard

C++基础语法 34、C++有哪几种的构造函数 (勘误+部分解释优化)

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;
		this->num = 1003;
    };
...
Student s3 = a; //转换构造函数调用
Student s4(s3);//重载构造函数调用
Student s5("fuck",56.45);//重载构造函数调用
Student s6 = 85.63;//转换构造函数调用

/*
s3 age:10, num:1002
s4 age:10, num:1002
s5 age:0, num:56
s6 age:85, num:1003
*/

YINGHAIDADA avatar Mar 12 '24 08:03 YINGHAIDADA