如何使用C++重載運算符&?我已經試過這樣:我該如何重載運算符&in 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
主要的Tne功能:
#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();
}
輸出結果:創建
對象。
通過'new'操作符創建的指針。
創建對象。
我的運營商&未被調用。爲什麼?
你這樣做:http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris 2013-04-23 12:29:45
嘗試'AB :: Object * ptrObj5 = obj1 & obj1;',你就會知道爲什麼。 – johnchen902 2013-04-23 12:31:59
我認爲你在這裏做什麼是一個非常糟糕的主意。操作員和參考計數會導致悲傷。 – 2013-04-23 12:33:52