1.友元类
如果StockManagement类要访问Stock类中私有成员,Stock类可以将StockManagement类声明为自己的友元类,具体实现如下:
class Stock
{
friend class StockManagement; //define the friend class
private:
char tag[5];
int cost;
long int volume;
public:
Stock(){strcpy(tag,"NULL");cost=0;volume=0;} //constructor
};
class StockManagement
{
private:
int size;
Stock *record;
public:
StockManagement(); //constructor
~StockManagement(); //destructor
void countRecords(ifstream &fd); //count records
void allocateMemory(); //allocate the dynamic memory
void loadRecords(ifstream &fd); //load records
void sortRecords(); //sort the records
void printRecords(ostream &out); //print out the records
};
下面以=为例,其他类似:
Stock & operator=(const Stock &s)
{
Stock temp;
strcpy(tag,s.tag);
cost=s.cost;
volume=s.volume;
return *this;
}
3.new结构体数组
分两种情况,一是已经声明了该结构体数组的情况下,给该数组分配内存
Stock *record;//不能为Stock record[];
record=new Stock[n];
第二种情况是数组声明和分配内存一起进行:
Stock *record=new Stock[n];