如何修复包含错误的错误必须返回值

How do I fix an error containing must return a value?

本文关键字:错误 返回值 包含 何修复      更新时间:2023-10-16

只是一个快速的问题,我不确定为什么要遇到此错误或如何修复它。

错误是C4176框:: getParameters:必须返回值。它说它必须返回值,但我确实将getParameter放在其中。我以前从未遇到过这个错误,我正在尝试弄清楚如何修复它。我目前正在尝试在我的OOP课程中创建类。

class Box
{
public:
    double height;//length of the box
    double depth;//depth of the box
    double width;//width of the box
    //Declare Member functions
    double getVolume(void);
    string getParameters(void);
    //Mutators
    void setHeight(double height);
    void setWidth(double width);
    void setDepth(double depth);
    //Accessors
    double getDepth(double depth);
    double getWidth(double width);
    double getHeight(double height);
}; //end class
//member function definitions
double Box::getVolume(void)//get volume will cal and output the volume when called
{
    return height * width * depth;
}
void Box::setDepth(double depth)
{
    depth = 0.01;
}
double Box::getDepth(double depth)
{
    return depth;
}
void Box::setWidth(double width)
{
    width = 0.01;
}
double Box::getWidth(double width)
{
    return width;
}
void Box::setHeight(double height)
{
    height = 0.01;
}
double Box::getHeight(double height)
{
    return height;
}
string Box::getParameters(void)
{
    cout << "nDepth:" << getDepth(depth) << endl <<
        "Width:" << getWidth(width) << endl <<
        "Height :" << getHeight(height) << endl;
}
int main()
{
    double depth;
    double width;
    double height;
    double volume;
    Box box;
    cout << "Please Enter a Length for your box: ";
    cin >> depth;
    box.setDepth(depth);
    cout << "Please Enter a Width for your box: ";
    cin >> width;
    box.setWidth(width);
    cout << "Please Enter a Height for your box: ";
    cin >> height;
    box.setHeight(height);
    //cout << "nn" << box.getParameters();
    volume = box.getVolume();
    cout << "nnThe Volume of your box is: " << volume;
    box.getParameters();
    return 0;
}

这是我的完整代码。有任何建议吗?

您的班级中有三种不同的方法。

第一个访问者(又名Getters)从类返回值,这些值不得具有参数,而返回类型的返回类型,以返回的任何值,因此,例如

// get the height of the box
double Box::getHeight()
{
    return height;
}

突变器(又称设置器)会在类中更改值,这些值应该具有一个参数,该参数是类的新值,并且void的返回类型(即它们不返回任何内容)。例如

// set the height of the box to h
void Box::setHeight(double h)
{
    height = h;
}

最后,有一些既不是登录器或突变器的方法,您的getParameters方法就是其中之一。对这些没有艰难而快速的规则,仅取决于他们的工作。您的getParameters方法实际上打印出某物,因此getParameters是一个坏名称,应称为printParameters。由于它所做的只是打印某些内容,因此它不应返回任何内容,因此它也不需要任何参数。这里应该如何写

// print the box parameters
void Box::printParameters()
{
    cout << "nDepth:" << getDepth() << endl <<
        "Width:" << getWidth() << endl <<
        "Height :" << getHeight() << endl;
}

保持更改简单,使用弦乐而不是stdout,然后返回字符串而不是打印到控制台

string Box::getParameters(void)
{
    std::stringstream ss;
    ss << "nDepth:" << getDepth(depth) << endl <<
        "Width:" << getWidth(width) << endl <<
        "Height :" << getHeight(height) << endl;
    return ss.str();
}