对运算符定义c ++的误解

Ana*_*ass 0 c++ operator-overloading

我试图理解为什么在调用时没有为此类定义的运算符(<)被执行:

//File A.h (simplified class)
#ifndef __A__H
#define __A__H

#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;

class A {

private:
    string _str;
    int _number;

public:
    A( string str="", int age=0): _str(str), _number(number){} //inline

    int operator < (const A &a1 ) const 
    {
        cout<<"Call of new operator <"<<endl;

        if ( _str == a1._str )
            return _number < a1._number; 
        return _str < a1._str; //here use of (<) associated to string 
     }

};
#endif

int main()
{
    A *obj1= new A("z",10);
    A *obj2= new A("b",0);
    int res=obj1<obj2; //res is equal to 1. There's no message              
                       // call of new operator"

    return 0;

} 
Run Code Online (Sandbox Code Playgroud)

我所学到的是,操作员的重新定义允许其通话.有帮助吗?谢谢

Cor*_*mer 5

obj1obj2A*A那么你正在做的是比较指针地址.如果你想使用A::operator<那么你需要取消引用你的指针

*obj1 < *obj2
Run Code Online (Sandbox Code Playgroud)

你也为什么还要operator<退货int呢?它应该返回一个bool.