operator->重载问题总结
class A
{
};
int main()
{
}
发现编译不过去,想一想也对, A&operator->()这个按照正常的重载方法必须要有参数,比如a->i,则应为A&operator->(inti)。a->print(200),参数必须为函数。这又让我比较纠结了。考虑到这里想不"->"操作符的重载必然不是这种方法,但是我记得以前看过的书中又提到->重载的,却想不起来是那本书,在哪里。于是把c++primer翻出来看了一下,没找到!又找了一下more effective c++也没找到。后来偶然在thinking inc++中看到了,虽然以前看过这本书,不过现在想来当时看的太不仔细了。不过由此也让我知道了->操作符重载与其他操作符重载不同的地方!
#include <iostream>
#include <vector>
#include "../require.h"
using namespace std;
class Obj {
static int i,j;
public:
void f()
const { cout<< i++<< endl; }
void g()
const { cout<< j++<< endl; }
};
// Static member definitions:
int Obj::i = 47;
int Obj::j = 11;
// Container:
class ObjContainer {
vector<Obj*>a;
public:
void add(Obj* obj){ a.push_back(obj); }
friend classSmartPointer;
};
class SmartPointer {
ObjContainer& oc;
int index;
public:
SmartPointer(ObjContainer& objc): oc(objc) {
index = 0;
}
// Return value indicates end of list:
bool operator++() {// Prefix
if(index >=oc.a.size())
return false;
if(oc.a[++index] == 0)
return false;
return true;
}
booloperator++(int) { // Postfix
return operator++(); // Use prefix version
}
Obj* operator->() const {
require(oc.a[index] != 0,"Zero value "
"returnedby SmartPointer::operator->()");
return oc.a[index];
}
};
int main() {
const int sz = 10;
Obj o[sz];
ObjContainer oc;
for(
int i = 0; i< sz; i++)
oc.add(&o[i]); // Fill it up
SmartPointer sp(oc); // Create an iterator
do {
sp->f(); // Pointer dereferenceoperator call
sp->g();
} while(sp++);
}
#include <vector>
#include "../require.h"
using namespace std;
class Obj {
public:
};
// Static member definitions:
int Obj::i = 47;
int Obj::j = 11;
// Container:
class ObjContainer {
public:
};
class SmartPointer {
public:
};
int main() {
}