#include<string>#include<iostream>classMyString{private:std::stringm_string;public:MyString(intx)// allocate string of size x{m_string.resize(x);}MyString(constchar*string)// allocate string to hold string value{m_string=string;}friendstd::ostream&operator<<(std::ostream&out,constMyString&s);};std::ostream&operator<<(std::ostream&out,constMyString&s){out<<s.m_string;returnout;}voidprintString(constMyString&s){std::cout<<s;}intmain(){MyStringmine='x';// Will compile and use MyString(int)std::cout<<mine<<'\n';printString('x');// Will compile and use MyString(int)return0;}
#include<string>#include<iostream>classMyString{private:std::stringm_string;public:// explicit keyword makes this constructor ineligible for implicit conversionsexplicitMyString(intx)// allocate string of size x{m_string.resize(x);}MyString(constchar*string)// allocate string to hold string value{m_string=string;}friendstd::ostream&operator<<(std::ostream&out,constMyString&s);};std::ostream&operator<<(std::ostream&out,constMyString&s){out<<s.m_string;returnout;}voidprintString(constMyString&s){std::cout<<s;}intmain(){MyStringmine='x';// 编译错误,因为 MyString(int) 现在是 explicit 的std::cout<<mine;printString('x');// 编译错误,MyString(int) 不能被用于隐式类型转换return0;}
#include<string>#include<iostream>classMyString{private:std::stringm_string;MyString(char)// objects of type MyString(char) can't be constructed from outside the class{}public:// explicit keyword makes this constructor ineligible for implicit conversionsexplicitMyString(intx)// allocate string of size x{m_string.resize(x);}MyString(constchar*string)// allocate string to hold string value{m_string=string;}friendstd::ostream&operator<<(std::ostream&out,constMyString&s);};std::ostream&operator<<(std::ostream&out,constMyString&s){out<<s.m_string;returnout;}intmain(){MyStringmine('x');// compile error, since MyString(char) is privatestd::cout<<mine;return0;}
#include<string>#include<iostream>classMyString{private:std::stringm_string;public:MyString(char)=delete;// 任何使用该函数的地方都会报错// explicit 使得该构造函数不能够被用于隐式类型转换explicitMyString(intx)// allocate string of size x /{m_string.resize(x);}MyString(constchar*string)// allocate string to hold string value{m_string=string;}friendstd::ostream&operator<<(std::ostream&out,constMyString&s);};std::ostream&operator<<(std::ostream&out,constMyString&s){out<<s.m_string;returnout;}intmain(){MyStringmine('x');// compile error, since MyString(char) is deletedstd::cout<<mine;return0;}