【发布时间】:2015-10-28 19:17:30
【问题描述】:
这个程序包含三个部分:标题、类的函数和交互的主要部分。但是,它不会编译。
我不断收到预期构造函数、析构函数或类型转换的响应。
#ifndef BOX_H
#define BOX_H
class Box
{
private:
double height;
double width;
double length;
public:
Box();
double setHeight();
double setWidth();
double setLength();
double getVolume();
double getSurfaceArea();
};
#endif
function.cpp:
#include "Box.hpp"
/**********************************************************************
Box:: Box
This is the default constructor that uses the set methods to initialize each field to 1.
* **********************************************************************/
Box::Box()
{
height = 1;
width = 1;
length = 1;
}
/*
Does anyone know what this section does? Is it another default constructor or is is it even needed?
Box::Box(double height, double width, double length)
{
setHeight(height);
setWidth(width);
setLength(length);
}
*/
double Box::setHeight()
{
return height;
}
double Box::setWidth()
{
return width;
}
double Box::setLength()
{
return length;
}
double Box::getVolume()
{
return height * width * length;
}
double Box::getSurfaceArea()
{
double SurAre = 0;
SurAre = (2 * (length * width)) + (2 * (length * height)) + (2 * (height * width));
return SurAre;
}
main.cpp:
#include <iostream>
#include "Box.hpp" //contains Box class declaration
using namespace std;
int main()
{
Box object;
double Alength;
double Awidth;
double Aheight;
cout << "This program will calculate the area of a box.\n";
cout << "What is the length?";
cin >> Alength;
cout << "What is the width?";
cin >> Awidth;
cout << "What is the height?";
cin >> Aheight;
object.setLength(Alength);
if (!object.setWidth(Awidth))
cout << "Invalid box width entered. \n" << endl;
if (!object.setHeight(Aheight))
cout << "Invalid box height entered. \n" << endl;
cout << "Volume: " << object.getVolume() << endl;
cout << "Surface Area: " << object.getSurfaceArea() << endl;
return 0;
}
有人知道为什么吗?
【问题讨论】:
-
粘贴exact错误信息。
-
“本节”所做的是提供三参数构造函数的主体。它不是默认构造函数——可以不带参数调用它们。可悲的是,它也不是好的 C++ 风格,看起来像是 Java 程序员做的。
-
1.使用初始化列表。 2.不要写这样的代码。它损害了封装的所有原则。 IMO,在这里使用命名空间会更合适。不过,作为一个例子,它没关系。 3. 你的 setter 不接受任何参数。
-
您听说过
const关键字吗?阅读相关内容可能很有用 -
它声明 - “Box::setLength(double&)”没有拟合函数 - 候选者是“double Box::setLength()
标签: c++