作业:
答案参照课堂Code-0521
class MyString{
public:
MyString();//返回空串
MyString(const char*p);//若p不为空,正常拷贝,为空,则返回空串
MyString(const MyString& obj);
~MyString();
//赋值运算符重载
MyString& operator=(const char*p);//s="a";
MyString& operator=(const MyString& s);//s=s1;
//[]
char &operator[](int index);//s[index]
//<< cout<<s4
friend ostream& operator<<(ostream&out,MyString& obj);
friend istream& operator>>(istream&in,MyString& obj);
//== if(s2=="s2")或者if(s3==s2)
bool operator==(const char*p)const;//this指针不能变
bool operator==(const MyString&s)const;
//!=
bool operator!=(const char*p)const;
bool operator!=(const MyString&s)const;
//< if(s<"bbb")或者if(s3<s2)
int operator<(const char* p);
int operator<(const MyString& s);
int operator>(const char* p);
int operator>(const MyString& s);
private:
int m_length;
char *m_Space;
};
重载()运算符和函数调用
class F{
public :
double operator ( ) ( double x , double y ) {
return x * x + y * y ;
}
};
void main ( )
{
F f ;
f.getA();
cout << f ( 5.2 , 2.5 ) << endl ; // ---->f . operator() (5.2, 2.5)
}
逻辑&&和||能否重载?
请参照课件。
&&和||内置实现了短路规则
操作符重载是靠函数重载来完成的
操作数作为函数参数传递
C++的函数参数都会被求值,无法实现短路规则
待补充:常对象,常成员函数
类的成员函数可被const修饰,那么const修饰的是?
void function()const ?
结论:const修饰的是this指针所指向的内存空间。