首页 > 代码库 > C++ explicit 关键字
C++ explicit 关键字
explicit 修饰只有一个参数的构造函数,以防止从参数类型到目标类类型的隐式转换。
// stdmove.cpp -- using std::move() #include <iostream> #include <utility> using std::cout; using std::endl; // use the following for g++4.5 // #define nullptr 0 // interface class Useless { private: int n; // number of elements char * pc; // pointer to data static int ct; // number of objects public: Useless(); explicit Useless(int k); Useless(int k, char ch); Useless(const Useless & f); // regular copy constructor ~Useless(); Useless & operator=(const Useless & f); // copy assignment void ShowObject() const; }; // implementation int Useless::ct = 0; Useless::Useless() { cout << "enter " << __func__ << "()\n"; ++ct; n = 0; pc = nullptr; ShowObject(); cout << "leave " << __func__ << "()\n"; } Useless::Useless(int k) : n(k) { cout << "enter " << __func__ << "(k)\n"; ++ct; pc = new char[n]; ShowObject(); cout << "leave " << __func__ << "(k)\n"; } Useless::Useless(int k, char ch) : n(k) { cout << "enter " << __func__ << "(k, ch)\n"; ++ct; pc = new char[n]; for (int i = 0; i < n; i++) pc[i] = ch; ShowObject(); cout << "leave " << __func__ << "(k, ch)\n"; } Useless::Useless(const Useless & f): n(f.n) { cout << "enter " << __func__ << "(const &)\n"; ++ct; pc = new char[n]; for (int i = 0; i < n; i++) pc[i] = f.pc[i]; ShowObject(); cout << "leave " << __func__ << "(const &)\n"; } Useless::~Useless() { cout << "enter " << __func__ << "()\n"; ShowObject(); --ct; delete [] pc; cout << "leave " << __func__ << "()\n"; } Useless & Useless::operator=(const Useless & f) // copy assignment { cout << "enter " << __func__ << "(const &)\n"; ShowObject(); f.ShowObject(); if (this == &f) return *this; delete [] pc; n = f.n; pc = new char[n]; for (int i = 0; i < n; i++) pc[i] = f.pc[i]; ShowObject(); cout << "leave " << __func__ << "(const &)\n"; return *this; } void Useless::ShowObject() const { cout << "\t this=" << this << ", ct=" << ct; cout << ", pc=(" << n << ", " << (void*)pc << ", "; if (n == 0) cout << "(object empty)"; else for (int i = 0; i < n; i++) cout << pc[i]; cout << " )." << endl; } int main() { Useless obj1(10); Useless obj2=5; }
说明:
//显式调用构造函数 ”explicit Useless(int k);”
Useless obj1(10);
//隐式调用构造函数 ”explicit Useless(int k);”。由于有explicit修饰,发生编译错误。
//error: conversion from ‘int’ to non-scalar type ‘Useless’ requested
//Useless obj2=5;
本文出自 “用C++写诗” 博客,谢绝转载!
C++ explicit 关键字
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。