Class 成员函数在其他 类 C++ 中作为友元

Class member functions as friends in other classes C++

我必须 类 表示随机生成器。

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);
}

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

printFrequency 方法不需要任何 class 成员。 所以它可以从 class 定义中删除,并与 classes 共享。