Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
YINGHAIDADA opened this issue Mar 12, 2024 · 0 comments

Comments

@YINGHAIDADA
Copy link
Contributor

勘误:

//语句打印 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
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant