2.non-explict it one arguement construct1.explict 关键字
1).C++中 ,explicit 关键字 主要修饰类的 构造函数,被修饰构造函数的类,不能发生相应隐式类型转换,只能以显示的方式进行类型转换。
2).注意事项:
<1>. explicit 只能用在类内部的构造函数声明上。
<2>.explicit 作用域单个参数的构造函数上(或是 只有一个参数不是默认值,其他参数都有默认值 也可以)。
<3>.explicit 被修饰的构造函数的类,不能发生相应的隐式类型转换。
例如:
[1].下面代码片段是 没有使用关键字 explicit 。point1 = 100;
<1>.这个先是 隐式转换成 Point 类型,何以见得呢?因为他进行了构造器 打印输出了 -> "构造 Point "
<2>.然后赋值操作,因为进入 赋值操作符 重载函数 。打印了 -> "Point = 赋值 "
class Point
{
private:
int x;
int y;
public:
Point(int _x = 0, int _y = 0) :x(_x), y(_y)
{
std::cout << "构造 Point "<< std::endl;
}
Point(const Point & other)
{
x = other.x;
y = other.y;
}
Point &operator=(const Point &other)
{
std::cout << "Point = 赋值 " << std::endl;
if (&other == this)
{
return *this;
}
x = other.x;
y = other.y;
return *this;
}
};
void test()
{
Point point1(5, 10);
point1 = 100;//通过 编译 //先进行构造 然后进行 赋值操作
}
[1].下面代码片段是 使用关键字 explicit 。point1 = 100;
<1>.vs2015 环境下的报错
error C2679: 二进制“=”: 没有找到接受“int”类型的右操作数的运算符(或没有可接受的转换)
可能是“Point &Point::operator =(const Point &)
尝试匹配参数列表“(Point, int)”时
class Point
{
private:
int x;
int y;
public:
explicit Point(int _x = 0, int _y = 0) :x(_x), y(_y)
{
std::cout << "构造 Point "<< std::endl;
}
Point(const Point & other)
{
x = other.x;
y = other.y;
}
Point &operator=(const Point &other)
{
std::cout << "Point = 赋值 " << std::endl;
if (&other == this)
{
return *this;
}
x = other.x;
y = other.y;
return *this;
}
};
void test()
{
Point point1(5, 10);
point1 = 100;//报错
}
void test()//把上面test函数修改如下 就可以正常编译通过了
{
Point point1(5, 10);
point1 = Point(100);//用类提供的构造器 去构造一个新的类 编译通过正确
}
总结:explict 避免隐式类型转换 产生的错误BUG,必须按照类正确构造方式进行构造。
1.Conversion Function转换函数
class Fraction{
public:
operator double() const {//转换不可能改变类里的成员,通常加上const
return (double)(m_numerator / m_denominator);
}//把Fraction对象转换成double类型,double()不可有参数,返回类型不用写
private:
int m_numerator;
int m_denominator;
};
Fraction f(3,5);
double d=4+f;//调用operator double()将f转为0.6
3.pointer-like classes,
template <typename T>
class shared_ptr
{
public:
T& operator*() const
{
return *px;
}
T* operator->() const{
return px;
}
shared_ptr(T* p) :px(p) { }
private:
T* px;//指向T的指针,什么类型都接受
long* pn;
};
class Foo
{
//...
void method(void)
{
//...
}
};
shared_ptr sp(new Foo);
Foo f(*sp);
sp->method();//调用method()
px->method();//通过这个对象调用这个函数
箭头符号有一个特殊的行为:作用下去得到的结果,这个箭头符号会继续作用下去
智能指针里头一定带着一个一般的指针,而智能指针一定要带*和->符号
point - class这种类型
4迭代器 主要用来遍历容器