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

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方法不需要任何类成员。
因此可以将其排除在类定义之外,并与两个类共享。

关于c++ - 类成员作为其他类C++中的 friend 起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33306076/

10-10 12:47