本文共 2782 字,大约阅读时间需要 9 分钟。
explicit 修饰只有一个参数的构造函数,以防止从参数类型到目标类类型的隐式转换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | // 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;