C++ explicit 关键字

本文介绍了C++中explicit关键字的作用及使用方法。该关键字用于防止构造函数被用作隐式类型转换,通过示例展示了正确使用explicit关键字的方式,并强调了其在避免潜在编程错误中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 /*
2 *C++ explicit 关键字
3 *
4 *It prevents constructor class from being used to perform implicit type conversion
5 *
6 *Author: MagicYun star3012@qq.com
7 *
8 */
9
10
11 #include <iostream>
12  using namespace std;
13
14 class Student
15 {
16 public:
17 Student(int age){};
18 ~Student(){};
19 };
20
21 class Animal
22 {
23 public:
24 explicit Animal(float weight){};
25 ~Animal(){};
26 };
27
28 int main()
29 {
30 Student Hui(110); //fine
31 Student Liang = 140; //fine
32
33 Animal pig(180.0); //fine
34 //Animal bird = 1.8; //error: conversion from `double' to non-scalar type `Animal' requested
35 return 0;
36 }

转载于:https://www.cnblogs.com/snowbee/archive/2011/04/11/2013032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值