如何在 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/