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;
时间: 2024-10-19 01:44:37