C ++运算符重载问题

时间:2018-11-10 06:00:30

标签: c++

我的任务是使用运算符重载

  1. 创建一个随机数数组
  2. 获取最低号码
  3. 获得最高号码
  4. 获取平均值
  5. 总计并
  6. 获取标准偏差。

那只是一团糟。这是我的代码:

#ifndef ASSIGNMENT6_HEAD6_H
#define ASSIGNMENT6_HEAD6_H

#include <iostream>
using namespace std;

class Analyzer {

    //Private Member
private:
    int numbers;

    //Public Member
public:
    Analyzer();//default constructor
    ~Analyzer();//destructor
    Analyzer operator+(const Analyzer &a) const;

    friend numbers operator+();


};//end of class

#endif //ASSIGNMENT6_HEAD6_H

//Class math with overloading operator and friends
#include "head6.h"
#include <cmath>
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;

vector<int> numbers;
int min = numbers[0];
int max = numbers[0];
int sizeofArray;
Analyzer::Analyzer() {

}
int getLowest(const int[], int);
//Random number member
void randNumbers(int sizeofArray, int* numbers[]) {
    for (int index = 0; index < sizeofArray; index++)
    {
        numbers[index] = (numbers() % 499) + 100;

    }return;
}
//Setters
int lowest = getLowest(numbers, sizeofArray);
int highest = getHighest(numbers, sizeofArray);
float total = getTotal(numbers);
double average = getAverage(total, sizeofArray);
//Lowest number
void getLowest(const int numbers[], int sizeofArray) {
    for (int i = 0; i < sizeofArray; i++) {
        if (min > numbers[i]) {
            min = numbers[i];
            min = lowest;
        }
    }
    return;
}
//Highest number
void getHighest(const int numbers[], int sizeofArray) {
    for (int i = 0; i < sizeofArray; i++) {
        if (max > numbers[i]) {
            max = numbers[i];
            max = lowest;
        }
    }
    return;
}
//Total
float getTotal(const int numbers) {
    total = sum(numbers[]);
    return total;
}
//Average
double getAverage(const float total, int sizeofArray) {
    double average = total / sizeofArray;
    return average;
}
//standard deviation
float  getStandardDeviation(int sizeofArray, float numbers[])const
{
    float deviation1;
    for (int i = 0; i < sizeofArray; i++)
        sum = (mean - numbers[i]) * (mean - numbers[i]);

    deviation1 = sqrt(sum / sizeofArray - 1);
    float deviation = deviation1;

    return deviation;
}

string a() {
    stringstream sout;
    sout << "STATISTICAL ANALYSIS OF RANDOMLY GENERATED NUMBERS" << endl;
    sout << "====================================================" << endl;
    sout << left << "Lowest Number:" << left << getLowest() << endl;
    sout << left << "Highest Number:" << left << getHighest() << endl;
    sout << left << "Numbers Total:" << left << getTotal() << endl;
    sout << left << "Numbers Averge:" << left << getAverage() << endl;
    sout << left << "Numbers of Standard Deviation:" << left <<
        getStandardDeviation() << endl;
    return sout.a();
}

int ​​main()
{
    Analyzer a;

    a + 100;
    cout << a;

    return 0;
}

谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您的任务是使用运算符重载来解决问题-但是您实际上并没有在任何地方(除了operator+类的Analyzer之外没有这样做)。< / p>

阅读您的台词,我想假设您应该为每个任务编写单独的类:

class Minimum
{
    std::vector<int> const& values
    public:
    Minimum(std::vector<int> const& values) : values(values) { }
    // calculates minimum / lowest value from member:
    int operator()();
};
class Maximum
{
    public:
    //Maximum(); not needed in this variant

    // calculates maximum from parameter
    int operator()(std::vector<int> const& values);
};

void test()
{
    std::vector<int> values({10, 12, 7});
    int min = Minimum(values)();
    int max = Maximum()(values);
}

这是两种不同的模式,为了保持一致性,您应该选择一种并实现所有类。在第一种方法中,您可以从任何成员函数访问向量,而不必将其作为参数传递;在第二种方法中,您可以重用一个和相同的对象来计算多个不同向量的值(您仍然可以保持指向向量的指针,以避免通过参数传递它。)

回到您的原始代码,很遗憾,该错误满了

vector<int> numbers;
int min = numbers[0]; // vector is yet empty! undefined behaviour!
int max = numbers[0];

实际上,您可能根本不想使用全局变量,请参阅稍后...

//int sizeofArray; // use numbers.size() instead!

// not an error, but questionable: you have a std::vector already, why do you
// fall back to C-style raw arrays?
void randNumbers(int sizeofArray, int* numbers[])
//                                   ^ array of pointers???
{
    for (int index = 0; index < sizeofArray; index++)
    {
        numbers[index] = (numbers() % 499) + 100;
        // you certainly intended to use rand function
    }
    // return; // just plain obsolete
}

// vector variant:
void randNumbers(unsigned int numberOfValues, std::vector<int>& destination)
//                            ^ not how many numbers ARE in,
//                              but how many SHALL be inserted
{
    // assuming we want to re-use this function and guarantee that EXACTLY
    // 'numberOfValues' values are contained:
    destination.clear(); // there might have been some values in already...

    // assure sufficently internal memory pre-allocated to prevent
    // multiple re-allocations during filling the vector:
    destination.reserve(numberOfValues);

    while(numberOfValues--)
    {
        numbers.push_back(rand() * 500 / RAND_MAX + 100);
        // modulus is unprecise; this calculation will give you better
        // distribution
        // however, rather prefer modern C++ random number generators!
        // IF you use rand: assure that you call srand, too, but exactly ONCE,
        // best right when entering main function
    }
}

// C++ random number generator:
void randNumbers(unsigned int numberOfValues, std::vector<int>& destination)
{
    static std::uniform_int_distribution<> d(100, 599);
    static std::mt19937 g;

    destination.clear();
    destination.reserve(numberOfValues);
    while(numberOfValues--)
    {
        numbers.push_back(d(g));
    }
}

现在您有矛盾的函数声明:

int  getLowest(const int[], int);
void getLowest(const int numbers[], int sizeofArray) { /* ... */ }

int lowest = getLowest(numbers, sizeofArray);
// again: the vector is yet empty!
// so you certainly won't get the result desired
// however, this won't compile at all: numbers is a std::vector,
// but parameter type is array, so you need:
int lowest = getLowest(numbers.data(), numbers.size());
//                                     ^ replaced the redundant global as well
// move this into your main function AFTER having filled the vector!

// picking int as return value:
int getLowest(const int numbers[], unsigned int sizeofArray)
{
    // you'd now have to initialize the global first; better, though:
    // return a local variable:

    // this assumes that there is at least one element in! check before usage
    // and decide what would be the appropriate error handling if the vector
    // is empty (return 0? return INT_MIN? throw an execption?)
    int min = numbers[0];

    for (int i = 1; i < sizeofArray; i++)
    {
        if (min > numbers[i])
        {
            min = numbers[i];
            // min = lowest; // don't overwrite the minimum again!
        }
    }

    // returning at end of void function is obsolete, don't do that explicitly
    // well, with int as return value, as is NOW, you NEED to return:
    return min;
}

最大程度地类似,请注意,您没有将比较从>更改为<!请注意,已经有std::min_elementstd::max_elementstd::minmax_element做同样的事情(如果作业未禁止这样做,您应该使用它们而不是重新发明轮子)。

// prefere double! float (on typical machines at least) has same size as int
// and it is quite likely that you will lose precision due to rounding; I
// personally would rather use int64_t instead, so you won't run into rounding
// issues even with double and you'd need quite a large amount of summands
// before overflow can occur...
float getTotal(const int numbers) // just one single number???
{
    total = sum(numbers[]);
    // index operator cannot be applied on a single int; additionally, you need
    // to provide an argument; where is 'sum' function defined at all???

    return total;
}

// prefer double again
double getStandardDeviation(int sizeofArray, float numbers[]) // const
// (free standing functions cannot be const)
{
    // mean isn't declared/defined anywhere (average instead?)!
    // and you need to declare and initialize the sum appropriately:
    double sum = 0.0;

    float deviation1;
    for (int i = 0; i < sizeofArray; i++)
        sum += (mean - numbers[i]) * (mean - numbers[i]);
    //      ^ you need to add, if you want to build sum

    // why two variables, even both of same type???
    deviation1 = sqrt(sum / sizeofArray - 1);
    float deviation = deviation1;

    return deviation;

    // simplest: drop both deviation and deviation 1 and just do:
    return sqrt(sum / sizeofArray - 1);
}

最后:除了重新打印输出到控制台之外,我认为您不会将结果字符串(在下面)用于其他任何事情,因此我将直接输出到std::cout(将函数命名为'print' );如果有的话,我会提供一个std::ostream作为参数,以使其更加灵活:

void print(std::ostream& sout)
{
    sout << "STATISTICAL ANALYSIS OF RANDOMLY GENERATED NUMBERS" << endl;
    sout << "====================================================" << endl;
    sout << left << "Lowest Number:" << left << getLowest() << endl;
    sout << left << "Highest Number:" << left << getHighest() << endl;
    sout << left << "Numbers Total:" << left << getTotal() << endl;
    sout << left << "Numbers Averge:" << left << getAverage() << endl;
    sout << left << "Numbers of Standard Deviation:" << left
         << getStandardDeviation() << endl;
}

现在您可以将std::cout传递到std::ostringstream对象,甚至可以通过std::ofstream ...写入文件

int ​​main()
{
    Analyzer a, b, c; // b, c added by me for illustration only

    a + 100;
    // the operator accepts another Analyzer object, so you could do
    c = a + b;

    cout << a; // there's no operator<< overload for Analyzer class


    // it is HERE where you'd call all your getXZY functions!

    return 0;
}

答案 1 :(得分:0)

您正在传递一个指向整数数组的指针:

void randNumbers(int sizeofArray, int* numbers[])

您实际上只想将数字作为数组传递。而且由于所有数组在作为参数传递时都会降级为指针,因此您的功能很简单:

void randNumbers(int sizeofArray, int* numbers) {

    for(int index = 0; index < sizeofArray; index++) {
        numbers[index]= (rand() % 499) + 100;
    };

}

结果是numbers中的项目将是[100..599]范围内的整数。