开发者

Implementing a multiplier in a statistician class

开发者 https://www.devze.com 2023-04-03 15:29 出处:网络
I am working on a programming assignment for my data structures class and we are working on making a statistician class. One of the functions that we have to have is to be able to take a statistician

I am working on a programming assignment for my data structures class and we are working on making a statistician class. One of the functions that we have to have is to be able to take a statistician list (count, sum, min, max and mean) and multiply it by a certain integer. Below is what i have so far for the specific function. However, i am lost about where to go as it seems to be worng.

statistician operator *(double scale, const statistician& s)
{
    scale*s;
    return s;
}

Attached is the .h file that explains what i am trying to do. i am writing the implementation 开发者_StackOverflow中文版file for this .h file and am trying to figure how to write the statistician operator* that is defined in the comments of the .h file

http://www.cs.colorado.edu/%7Emain/projects/stats.h

Thanks for any help


The code you wrote looks like it will compile, but causes an infinite loop, since it calls itself. scale*s is a shortcut for operator*(scale, s), which is the function currently being defined. You need to replace the line scale*s with baby-steps for the compiler. It'll look something like:

statistician operator *(double scale, const statistician& s)
{
    statistician result
    result.count = /*???*/;
    result.total = /*???*/;
    /*etc*/;
    return result;
}

Once that's defined, you may also want statistician*double, which can simply do what you've programmed as double*statistician like so. (Note that it doesn't need to be a friend class, since it only calls public functions)

statistician operator *(const statistician& s, double scale)
{
    return operator *(scale, s);
}


You are trying to create a copy of the class statistician, but scaled by scale. Something like

statistician operator *(double scale, const statistician& s)
{
    statistician result(s);
    result.total *= scale;
    result.tinyest *= scale;
    result.largest *= scale;
    return result;
}

The member function scaleBy would multiply the appropriate member variables by the appropriate scale.

You wouldn't scale the count. If you had something like variance in your statistician class, you would probably multiply it by the square of scale.


Are you trying to implement the operator inside the class, or outside of the class? Read up on Operators in C++, and decide!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号