C++内部类访问外部类
采用如下的方式訪問外部類:
// OperatorTest.cpp : 此文件包含 "main" 函數。程序執行將在此處開始并結束。
//
#include <iostream>
#include<vector>
using namespace std;
class Obj {
?? ?static int i, j;
public:
?? ?void f() {
?? ??? ?cout << "i:" << i++ << endl;
?? ?}
?? ?void g() {
?? ??? ?cout << "j:" << j++ << endl;
?? ?}
};
int Obj::i = 11;
int Obj::j = 12;
class ObjContainer {
?? ?vector<Obj*> objs;
public:
?? ?class SmartPointer;
?? ?friend class SmartPointer;
?? ?void add(Obj* obj) {
?? ??? ?objs.push_back(obj);
?? ?}
?? ?class SmartPointer {
?? ??? ?ObjContainer& oc;
?? ??? ?int index;
?? ?public:
?? ??? ?SmartPointer(ObjContainer& oc):oc(oc){
?? ??? ??? ?index = 0;
?? ??? ?}
?? ??? ?bool operator++() {
?? ??? ??? ?index++;
?? ??? ??? ?if (index >=oc.objs.size())return false;
?? ??? ??? ?if (oc.objs[index] == 0)return false;
?? ??? ??? ?return true;
?? ??? ?}
?? ??? ?bool operator++(int) {
?? ??? ??? ?return operator++();
?? ??? ?}
?? ??? ?Obj* operator->() {
?? ??? ??? ?return oc.objs[index];
?? ??? ?}
?? ?};
?? ?SmartPointer begin() {
?? ??? ?return SmartPointer(*this);
?? ?}
};
int main()
{
?? ?const int sz = 12;
?? ?ObjContainer oc;
?? ?Obj objs[sz];
?? ?ObjContainer::SmartPointer sp = oc.begin();
?? ?for (int i = 0; i < sz; i++) {
?? ??? ?oc.add(&objs[i]);
?? ?}
?? ?do {
?? ??? ?sp->f();
?? ??? ?sp->g();
?? ?} while (sp++);
}
?
總結
以上是生活随笔為你收集整理的C++内部类访问外部类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AbstractListView源码分析
- 下一篇: X265源码解析1-Encode方法