首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

==操作符重载作为成员函数如何书写

2013-08-04 
操作符重载作为成员函数怎么书写?bool operator(const Vector& a,const Vector& b){bool yes truei

==操作符重载作为成员函数怎么书写?


bool operator==(const Vector& a,const Vector& b)
{
bool yes = true;
if(a.size != b.size)
{
yes = false;
}
else
{
int index = 0;
int s = a.get_size();
while (index<s && a[index] == b[index])
{
++index;
}

if(index < s)
{
yes = false;
}
}
return yes;
}


这是作为普通函数的代码,帮我改写成成员函数吧
[解决办法]

friend bool Vector::operator==(const Vector & a); 

bool Vector::operator==(const Vector & a)
{
    bool yes = true;
    if(a.size != this->size)
    {   
        yes = false;
    }   
    else
    {   
        int index = 0;
        int s = a.get_size();
        while (index<s && a[index] == this[index])
        {   
            ++index;
        }   

        if(index < s)
        {   
            yes = false;
        }   
    }   
    return yes;
}

[解决办法]
将第一个参数视为this不就解决了吗。
[解决办法]
引用:

Quote: 引用:

将第一个参数视为this不就解决了吗。

我这里使用的get_size()的函数,能写成this.get_size()吗?
可以
顺便friend是不要的
[解决办法]
引用:
Quote: 引用:

将第一个参数视为this不就解决了吗。

我这里使用的get_size()的函数,能写成this.get_size()吗?



this->get_size(); //this是指针!

[解决办法]
// 类定义
//template<typename T>
class Vector{
.......
......
public:
//   Vector(const T *startaddr,const T *endaddr):p(NULL),size(endaddr-startaddr){
//    p=new T[size];//不处理异常 
//    if(!p)return ;
//    for(T *pcur = p;pcur < p + size;) *pcur++= *startaddr++;
//   };
// Vector():p(NULL),size(n){ };
//    Vector(int n):p(NULL),size(n){ p = new T[n]; };
//    ~Vector(){delete []p;};
    bool operator==(const Vector& b);//声明重载运算符函数
    //const T& operator [](int n)const { return p[n]; };   
    //T& operator [](int n) { return p[n];};   
   // int get_size()const{return size;};    
private:
    int size; 
    //T *p; 
    ......
};

//
//operator==() 函数类外定义
//template <typename T>bool Vector<T>::operator==(const Vector<T>& b) 
bool Vector::operator==(const Vector& b) { 
    if(size != b.size)
       return false;

    int index = 0;         
    //知道这个类,是怎么实现的话,直接用 p[index] == b.p[index] 
    // 替换 (*this) [index] == b[index])         
         
    while (index< size && (*this) [index] == b[index])          


        ++index;       
   retunr index == size;


大概如此吧;
PS:你要做的就是 用 "this->"  替换 "a."
*this 替换 a ,考虑到不清楚*和[] 的优先级,用(*this)代替*this。 
其中this-> 可以直接省略。
 


热点排行