C++多态-重载

C++多态-重载:

静态多态和动态多态:提高开发效率
函数重载与运算符重载
多态:一种定义多种实现->联系构造函数
函数名相同->同一块地址
编译器在底层会根据你传过来的参数转换为不同的函数
函数重载包括
1.普通函数
2.类成员函数(比普通函数少一个参数)
注:不要重复定义两类操作符重载函数
objdump -d a.out
函数重载->参数匹配精确匹配->隐式转换匹配(double遇到int 和float)
一般不采用变参函数
参数的类型和参数的顺序不同,函数名相同,返回值无关

class Point{
}
Point p1;
cout<<p1
此时需要重载ostream

ostream &&operator <<(ostream& os,const Point*p){
os<<"x="<<p.x<<"y="<<p.y;
return os;
}

++a//前++会带参数(int),后++不带参数作为区分

=,&操作符编译器会在底层进行重载
下面不能进行运算符重载:
?:(条件运算符)//三元操作符无法重载
.(成员访问运算符)
*(成员指针访问运算符)
:: //域运算符
sizeof()//是运算符,不是函数

Point operator+(const Point&p){
    Point ret(*this);
    ret._x+=p._x;
    ret._y+=p._y;
    return ret;
}
float operator*(const Point&p){
    return this->_x*p._x+this->_y*p._y;
}
Point p1(1.0f,2.45f),p2(5.23f,7.32f);
p1+p2;
p1*p2;
p1++;
p2++;
++p1;

仿函数:

//仿函数,可以传参数
// void print(int n,int x){
//     cout<<n*x+100;
// }
void print(int n){
    cout<<n*3+100<<" ";
}
class checkNumber{
private :
    int max;
    int min;
public:
checkNumber(int a,int b):min(a),max(b){

}
bool operator()(int n){
    if(n>=min&&n<=max)
      return true;
    return false;
}
}
class Print{
private: 
    int x;
public:
   void operator()(int n){
       cout<<"operator functor"<<n*3+100<<endl;
   }
   void call(){
         cout<<" operator functor"<<endl;
   }
};
int main(){
    Print p;
    //p.call();
    //p();
    vector<int>arr;
    arr.push_back(1);
    arr.push_back(2);
    arr.push_back(3);
    arr.push_back(4);
    for(auto it:arr){
        print(it,3);
        cout<<endl;
    }
    for_each(arr.begin(),arr.end(),print);
    cout<<"=====functor"<<endl;
    for_each(arr.begin(),arr.end(),Print(3));
    count_if(arr.begin(),arr.end(),checkNumber(1,500));
    cout<<"cout of 1-500="<<count2<<endl;
    return 0;
}

实现个人的Mystring:

#incldue<string>
using namedpace std;
namespace master{
    private:
    char*_data;
    int _length;
    int _capacity;
    int _offset;
    public:
    Mystring()=default;
    Mystring(const char*);
    Mystring(const Mystring&str);
    void operator=(const Mystring*str);
    char& operator[](int index);
    Mystring& operator+=(const char*);
    Mystring& operator+=(const MyString&);
    Mystring& operator+=(const std::string&);
    inline int size(){return _length;};
    int capacity(){return _capcity};
    void push_back(const char ch);
    void pop_back();
    void swap(Mystring& str);
};
ostream operator<<(ostream&os,const )
}
int main(){
   string str="123456";
   str+="123";
   str[0];
   str+"123;
   cout<<str;
   cin >> str;
   str.size();
   str.length();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值