标题文件:
// pe10-8arr.h -- header file for a simple list class
#ifndef SIMPLEST_
#define SIMPLEST_
// program-specific declarations
const int TSIZE = 45; // size of array to hold title
struct film
{
char title[TSIZE];
int rating;
};
// general type definitions
typedef struct film Item;
const int MAXLIST = 10;
class simplist
{
private:
Item items[MAXLIST];
int count;
public:
simplist(void);
bool isempty(void);
bool isfull(void);
int itemcount();
bool additem(Item item);
void transverse( void (*pfun)(Item &item));
};
#endif
使用标题的代码:
#include "pe10-8arr.h"
simplist::simplist(void)
{
count = 0;
}
bool simplist::isempty(void)
{
return count == 0;
}
bool simplist::isfull(void)
{
return count == MAXLIST;
}
int simplist::itemcount()
{
return count;
}
bool simplist::additem(Item item)
{
if (count == MAXLIST)
return false;
else
items[count++] = item;
return true;
}
void simplist::transverse( void (*pfun)(Item &item))
{
for (int i = 0; i < count; i++)
(*pfun)(items[i]);
}
#include <iostream>
#include <cstdlib> // prototype for exit()
#include "pe10-8arr.h" // simple list class declaration
// array version
void showmovies(Item &item); // to be used by transverse()
int main(void)
{
using namespace std;
simplist movies; // creates an empty list
Item temp;
if (movies.isfull()) // invokes isfull() member function
{
cout << "No more room in list! Bye!\n";
exit(1);
}
cout << "Enter first movie title:\n";
while (cin.getline(temp.title,TSIZE) && temp.title[0] != '\0')
{
cout << "Enter your rating <0-10>: ";
cin >> temp.rating;
while(cin.get() != '\n')
continue;
if (movies.additem(temp) == false)
{
cout << "List already is full!\n";
break;
}
if (movies.isfull())
{
cout << "You have filled the list.\n";
break;
}
cout << "Enter next movie title (empty line to stop):\n";
}
if (movies.isempty())
cout << "No data entered. ";
else
{
cout << "Here is the movie list:\n";
movies.transverse(showmovies);
}
cout << "Bye!\n";
return 0;
}
void showmovies(Item &item)
{
std::cout << "Movie: " << item.title << " Rating: "
<< item.rating << std::endl;
}
上面的代码只是编译并成功运行。任何人都可以告诉我为什么函数showmovies()
可以使用引用访问simplist
的项成员而不被声明为友元函数或成员函数?
答案 0 :(得分:9)
结构成员的默认可见性为public
。该功能仅使用Item
,而不是simplist
。
答案 1 :(得分:5)
showMovies
以Item
为参数。它不关心它是否是会员。
Item
是struct
,除非另有声明,否则其字段为public
。
答案 2 :(得分:0)
该函数被传递给Item
对象(通过引用),它不知道或关心它来自何处。该函数的调用者实际上是从整个对象中拉出对象的函数,但transverse
通过成为该类的成员来访问。
答案 3 :(得分:0)
里面简化:
void simplist::transverse( void (*pfun)(Item &item))
{
for (int i = 0; i < count; i++)
(*pfun)(items[i]);
}
您正在从横向(简化成员)调用showmovies,因此无论可见性如何,您都可以访问所有类属性。