1. 如何在一个模板类中访问一个具体实例类中的私有成员?举例如下
模板类定义:
#ifndef __N_H__
#define __N_H__
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class N
{
public:
void fun(T&t);
N(int sn);
private:
vector<T> veclist;
};
template<class T>
N<T>::N(int sn)
{
for (int i = 0; i < sn; i++) {
T obj(i);
veclist.push_back(obj);
}
}
template <class T>
void N<T>::fun(T& t)
{
t.f();
cout << "===========" << endl;
for(size_t i = 0; i < veclist.size(); i++) {
T obj = veclist[i];
cout << "A::a=" << obj.aa << endl;
}
}
#endif
头文件A.h:
#ifndef __A_H__
#define __A_H__
#include <stdio.h>
#include "N.h"
class A
{
public:
A(int x);
private:
void f();
int aa;
friend class N<A>;
};
#endif
#include "A.h"
A::A(int x)
{
aa = x;
}
void A::f()
{
printf("hello world-----------A f()\n");
}
主函数:
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
#include "A.h"
#include "N.h"
int main(int argc, char* argv[])
{
A a(111);
N<A> n(2);
n.fun(a);
return 0;
}
输出结果:
hello world-----------A f()
===========
A::a=0
A::a=1
2. 一个普通类中如何访问模板类中的私有成员?
模板类定义:
#ifndef __N_H__
#define __N_H__
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
class B; //-------1
template <class T>
class N
{
public:
void fun(T&t);
N(int sn);
N();
private:
vector<T> veclist;
friend class B; //--------------2
};
template <class T>
N<T>::N()
{
}
template<class T>
N<T>::N(int sn)
{
for (int i = 0; i < sn; i++) {
T obj(i);
veclist.push_back(obj);
}
}
template <class T>
void N<T>::fun(T& t)
{
t.f();
cout << "===========" << endl;
for(size_t i = 0; i < veclist.size(); i++) {
T obj = veclist[i];
cout << "A::a=" << obj.aa << endl;
}
}
#endif
类A的定义同上
类B定义:
头文件B.h:
#ifndef __B_H__
#define __B_H__
class B {
public:
B();
void Print();
private:
};
#endif
实现文件B.cpp
#include "B.h"
#include <iostream>
using namespace std;
#include "A.h"
#include "N.h"
extern N<A> n;
B::B()
{
}
void B::Print()
{
cout << "N::a=" << n.veclist.size() << endl;
}
主函数:
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
#include "A.h"
#include "N.h"
#include "B.h"
N<A> n;
int main(int argc, char* argv[])
{
A a(111);
//N<A> n(2);
n = N<A>(2);
n.fun(a);
B b;
b.Print();
return 0;
}