第11章 使用类
11.2.2
(1)重载限制:
[1]重载后的运算符必须至少有一个操作数是用户定义的类型,这将防止用户为标准类 型重载
[2]使用运算符使不能违反运算符原来的句法规则
[3]不能创新运算符
[4]不能重载的运算符
11.3友元函数
(1)类的友元函数是非成员函数,其访问权限与成员函数相同
(2)
#include<iostream>
using namespace std;
class A
{
private :
int m_n;
public :
A()
{
m_n=0;
}
A(int m_n)
{
this->m_n=m_n;
}
int operator *(int m_num) const//const A &a const对象只能访问const成员函数
{
return m_n*m_num;
}
friend int operator *(int m_num,const A &a);
};
int operator *(int m_num,const A &a)
{
return a*m_num;//如果要为重载运算符,并将非类的项作为其第一个操作数, 则可以用友元函数来反转操作数的顺序
}
int main()
{
A a(100);
cout<<a*2<<endl;
cout<<3560*a<<endl;
return 0;
}
(3)通过使用友元函数和类方法,可以使用同一个用户接口表达这两种操作
(4)只有类成员可以决定那一个函数是友元
(5)类成员和友员只是表达类接口的两种不同机制
11.3.2
(1) void operator<<(ostream &os,cosnt Time &t)
{
os<<t.hours<<”hours , “<<t.minutes<<” minutes”<<endl;
//os引用cout对象,但可以将运算符用于ostream对象,os将引用相应的
}
友元还是非友元?
ostrsam<<()直接访问Time对象的私有成员,所以必须是Time的友元,但是他并不直接访问ostream对象的私有成员所以并不一定是ostream类友元
(2)ostream &operator (ostream &os,const Time &t)
{
os<<t.hours<<”hours , “<<t.minutes<<” minutes”<<endl;
return os;
}
返回类型为ostream&。函数返回ostream对象的引用
11.4重载运算符:作为成员函数还是非成员函数
Time operator+(cosnt Time &t) const;//成员函数,一个操作数通过this指针隐式地传递,另一个作为函数参数显示地传递
friend operator + (csont Time &t1,cosnt Time &t2);//两个操作数都作为参数来传递
二义性错误
11.5.矢量类
11.6
(1)C++语言不自动转换不兼容类型,例如:int *p=10;非法,但可以强制类型转换 int *p=(int *)10;
(2)Stonewt myCat;
myCat = 19.6;//隐式类型转换
只有接受一个参数的构造函数再能作为转换函数
Stonewt (double lbs);
Stonewt(int stn,double lbs = 0);//如果第二个参数提供默认值,它便可用于转换int
(3)只接受一个参数的构造函数定义了从参数类型到类类型的转换。如果使用关键字elplicit限定了这种函数,着它只能用于显示转换,否则也可以用于隐式转换
11.6.1转换函数
(1)转换函数是用户定义的强制类型转换
(2)几点[1]转换函数必须是类方法
[2]转换函数不能又返回类型
[3]转换函数不能有这参数
operator int () cosnt ;
operator double() csont ;
long gone = poppins;//二义性
long gone = (double )poppins;
long gone = int (poppins);
(3)在C++11中
exiplicit operator int ()cosnt ;
exiplicit operator double ()const ;
需要强制转换调用这些运算符
(4)用一个功能相同的非转换换函数替换该转换函数,
但仅在被显示地调用,该函数才会执行
Stonewt ::operator int()
{
return int (pounds + 0.5);
}
int Stonewt::Stone_to_Int()
{
return int(pounds + 0.5);
}
(5)被称为转换函数的特殊类成员运算符函数,用于将类对象转换为其它类型。转换函数是类成员,没有返回类型,没有参数,名为operator typeName().
11.6.2转换函数和友元函数
Stonewt Stonewt ::operator(cosnt &Stonewt &st)const
{
double pds = pounds +st.pounds;
Stonewt sum(pds);
return sum;
}
Stonewt operator+(const Stonewt &st1,cosnt Stonewt &st2)
{
double pds =st1.pounds +st2.pounds;
Stonewt sum(pds);
return sum;
}
[2]提供Stonewt (double)构造函数
Stonewt jennySt(9,12);
Double pennyD = 146.0;
Stonewt total;
toal = jennySt + pennyD;
toal = jennySt.operator(pennyD);
toal = operator + (jennySt,pennyD);
pennyD 将调用 Stonewt(double) 构造函数,将该参数转换为Stonewt对象
[3]
实现加法的选择
[1]friend operator +(const Stonewt &,const Stonewt &)
让Stonewt (double)构造函数 将double 类型的参数转换为Stonewt参数
[2]将加法运算符重载为一个显示使用double类型的函数:
Stonewt operator(double +)
fiend Stonewt operator +(double x, Stonewt &s);
第11章 使用类
最新推荐文章于 2022-07-17 12:32:02 发布