类成员在其他类C ++中充当朋友

时间:2015-10-23 15:25:16

标签: c++ inheritance friend access-control friend-function

我必须使用代表随机生成器的类。

r_6.h

#include <vector>
#pragma once

class R_G_6 {
public:
    R_G_6() {};
    float getNextRand();
    void countFrequency();
    void printFrequency(vector<long>);
    vector<long>frequencies;
private:
    R_G_1 r_1;
    float sum;
    static const long m = 0;
    static const long sigma = 1;
};

r_6.cpp

#include r_6.h
float  R_G_6::getNextRand()
{
    sum = 0;
    int count = 0;
    while (count != 12)
    {
        sum += r_1.getNextRand();
        ++count;
    }
    return (m + (sum - 6)*sigma);
}

void R_G_6::countFrequency()
{
    vector<long>frequencies;
    for (int j = 0; j < 7; ++j)
        frequencies.push_back(0);
    const long maxRands = 1000;
    for (int i = 0; i < maxRands; ++i)
    {
        int r = getNextRand();
        frequencies[r] = frequencies[r] + 1;
    }
}

void R_G_6::printFrequency(vector<long>frequencies)
{
    if (frequencies.empty())
        cout << "You haven`t count frequency!" << endl;
    else
    {
        for (int i = -3; i < 3; ++i)
        {
            cout << "[" << i << ";" << i+1 << "]"
                << " | " << frequencies[i] << endl;
        }
    }
}

r_7.h

#include "r_1.h"
#include "r_6.h"
#include <vector>
#include <utility>
#pragma once

class R_G_7  {
public:
    R_G_7() {};
    pair<float, float> getNextRand();
    void countFrequency();
    friend void R_G_6::printFrequency(vector<long>);
    vector<long>frequencies;
private:
    R_G_1 r1;
};

r_7.cpp

pair<float, float> R_G_7::getNextRand()
{
    float v1, v2, s;
    while (true) {  
        v1 = 2 * (r1.getNextRand()) - 1;
        v2 = 2 * (r1.getNextRand()) - 1;
         s = v1*v1 + v2* v2;
        if (s < 1) break;
    }
    float x1, x2;
    x1 = v1*(sqrt((-2)*log(s) / s));
    x2 = v2*(sqrt((-2)*log(s) / s));
    return make_pair(x1, x2);
}

void R_G_7::countFrequency()
{
    for (int j = 0; j < 7; ++j)
        frequencies.push_back(0);
    const long maxRands = 1000;
    for (int i = 0; i < maxRands; i+=2)
    {
        pair<float, float> pair_num = getNextRand();
        int r1 = (pair_num.first);
        frequencies[r1] = frequencies[r1] + 1;
        int r2 = (pair_num.second);
        frequencies[r2] = frequencies[r2] + 1;
    }
}

我不认为这两个类可以或应该从彼此继承。而且我不会复制粘贴printFrequency(vector<long>frequencies)函数。所以我认为把它当作朋友是个好主意。但实际上我不能将它用于R_G_7类型的对象:

void rand_gen_6()
{
    R_G_6 r6;
    r6.countFrequency();
    r6.printFrequency(r6.frequencies); // it is OK
}

void rand_gen_7()
{
    R_G_7 r7;
    r7.countFrequency();
    // this is not OK
    // r7.printFrequency(r7.frequencies);  
    // or r7.R_G_6::printFrequency(r7.frequencies);
}

也许有人知道我的代码有什么问题或者如何解决我的问题。

1 个答案:

答案 0 :(得分:2)

printFrequency方法不需要任何类成员。 所以它可以放在类定义之外,并与两个类共享它。