运算符重载

作业:

答案参照课堂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指针所指向的内存空间。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • C++运算符重载-上篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 2,415评论 0赞 51
  • 基本上我们进行运算符重载时有两种形式,类内的运算符重载和顶层函数位置的运算符重载。 操作符重载指的是将C++提供的...
    飞扬code阅读 1,817评论 0赞 4
  • C++运算符重载-下篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 1,576评论 0赞 49
  • C++语言的一个很有意思的特性就是除了支持函数重载外还支持运算符重载,原因就是在C++看来运算符也算是一种函数。比...
    欧阳大哥2013阅读 2,803评论 0赞 8
  • C++运算符重载的实质:运算符重载的实质就是函数重载或函数多态。运算符重载是一种形式的C++多态。目的在于让人能够...
    Nancy_Shi阅读 1,129评论 1赞 3

友情链接更多精彩内容