c++ - 如何在 C++ 中重载运算符 &

标签 c++

如何在 C++ 中重载运算符&?我试过这个:

#ifndef OBJECT_H
#define OBJECT_H
#include<cstdlib>
#include<iostream>

namespace TestNS{

    class Object{
    private:
        int ptrCount;
    public: 
        Object(): ptrCount(1){           
            std::cout << "Object created." << std::endl;
        }
        void *operator new(size_t size);
        void operator delete(void *p);
        Object *operator& (Object obj);
    };

    void *Object::operator new(size_t size){            
            std::cout << "Pointer created through the 'new' operator." << std::endl; 
            return malloc(size);
        }

    void Object::operator delete(void *p){
            Object * x = (Object *) p;
            if (!x->ptrCount){
                free(x);
                std::cout << "Object erased." << std::endl;
            }
            else{
                std::cout << "Object NOT erased. The " << x->ptrCount << "references are exist." 
                    << std::endl;
            }
        }
    
    Object *Object::operator& (Object obj){
            ++(obj.ptrCount);
            std::cout << "Counter is increased." << std::endl;
            return &obj;
        }
}
#endif

主要功能:

#include<iostream>
#include"Object.h"

namespace AB = TestNS;

int main(int argc, char **argv){
    AB::Object obj1;
    AB::Object *ptrObj3 = &obj1; // the operator& wasn't called.
    AB::Object *ptrObj4 = &obj1; // the operator& wasn't called.

    AB::Object *obj2ptr = new AB::Object();
}

输出结果:

Object created.

Pointer created through the 'new' operator.

Object created.

我的接线员& 没有被叫到。为什么?

最佳答案

您当前正在重载二进制 & 运算符(即按位与)。要重载一元 & 运算符,您的函数不应采用任何参数。它适用的对象是 this 指向的对象。

Object *Object::operator& (){
    ++(this->ptrCount);
    std::cout << "Counter is increased." << std::endl;
    return this;
}

关于c++ - 如何在 C++ 中重载运算符 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16169349/

相关文章:

c++ - C++11 中的 const 类型到 const 别名

c++ - 如何创建带参数的成员函数指针数组?

c++ - 传递 'const Class2' 作为 'this' 的 'int Class1::get_data()' 参数丢弃限定符

没有指针的 C++ 多态性

c++ - 错误 C2065 : undeclared identifier in template function

c++ - 如何保证加载在存储发生之前完成?

c++ - 代码辅助,OpenGL VAO/VBO 类不绘制

c++ - 为什么 std::thread 在其构造函数中等待?

c++ - 引用的内存分配

c++ - 我可以使用 MS 工具将浮点错误转变为 C++ 异常吗?