重庆网站建设沛宣,门户网站的重要性,手机网站建设计,平面设计网站制作C中使用构造函数进行类型转换
可给类提供重载的构造函数#xff0c;即接受一个或多个参数的构造函数。这种构造函数常用于进行类型转换。请看下面的 Human 类#xff0c;它包含一个将整数作为参数的重构构造函数#xff1a;
class Human
{int age;public:Human(int humans…C中使用构造函数进行类型转换
可给类提供重载的构造函数即接受一个或多个参数的构造函数。这种构造函数常用于进行类型转换。请看下面的 Human 类它包含一个将整数作为参数的重构构造函数
class Human
{int age;public:Human(int humansAge): age(humansAge) {}
};// Function that takes a Human as a parameter
void DoSomething(Human person)
{cout Human sent did something endl;return;
}这个构造函数让您能够执行下面的转换
Human kid(10); // convert integer in to a Human
DoSomething(kid);这样的转换构造函数让您能够执行隐式转换
Human anotherKid 11; // int converted to Human
DoSomething(10); // 10 converted to Human!函数 DoSothing(Human person)被声明为接受一个 Human而不是 int参数前面的代码为何可行呢这是因为编译器知道 Human 类包含一个将整数作为参数的构造函数 进而替您执行了隐式转换将您提供的整数作为参数发送给这个构造函数从而创建一个 Human 对象。 为避免隐式转换可在声明构造函数时使用关键字 explicit
class Human
{int age;public:explicit Human(int humansAge): age(humansAge) {}
};并非必须使用关键字 explicit但在很多情况下这都是一种良好的编程实践。以下示例程序演示了另一个版本的 Human 类这个版本不允许隐式转换
#includeiostream
using namespace std;class Human
{int age;
public:// explicit constructor blocks implicit conversionsexplicit Human(int humansAge) : age(humansAge) {}
};void DoSomething(Human person)
{cout Human sent did something endl;return;
}int main()
{Human kid(10); // explicit converion is OKHuman anotherKid Human(11); // explicit, OKDoSomething(kid); // OK// Human anotherKid 11; // failure: implicit conversion not OK// DoSomething(10); // implicit conversion return 0;
}输出
Human sent did something分析 无输出的代码行与提供输出的代码行一样重要。这个 Human 类包含一个使用关键字 explicit 声明的构造函数如第 8 行所示而第 1727 行的 main()以各种不同的方式实例化这个类。使用 int 来实例化 Human 类的代码行执行的是显式转换都能通过编译。第 23 和 24 行涉及隐式转换它们被注释掉了但如果将第 8 行的关键字 explicit 删掉这些代码行也能通过编译。这个实例表明使用关键字 explicit 可禁止隐式转换。
提示
运算符也存在隐式转换的问题也可在运算符中使用关键字 explicit 来禁止隐式转换。该文章会更新欢迎大家批评指正。
推荐一个零声学院的C服务器开发课程个人觉得老师讲得不错 分享给大家LinuxNginxZeroMQMySQLRedis fastdfsMongoDBZK流媒体CDNP2PK8SDocker TCP/IP协程DPDK等技术内容 点击立即学习C/C后台高级服务器课程