问题#1:如何构建构造函数设置
(R,PoF,PoR)
的值?我试图理解构造函数是如何工作的,但我想我不太明白。问题#2:我可以用这种方式构建析构函数,而不是我在程序中使用的方式吗?
Circle::~Circle()
{
std::cout << "The fence would cost " << SwimmingPool.PerimeterP(r) << std::endl;
std::cout << "The road would cost " << SwimmingPool.AreaP(r) << std::endl;
std::cout << "Present by FF" << std::endl;
}
我只想让费用单独出来,但我不知道如何创建析构函数。
以下是我的完整代码:
#include "stdafx.h"
#include "iostream"
const double PI = 3.1415926;
class Circle
{
public:
Circle();
double AreaP(int r);
double PerimeterP(int r);
~Circle();
private:
int R;
int PoF;
int PoR;
};
double Circle::AreaP(int r)
{
return ((r + R)*(r + R) - r*r)*PI*PoR;
}
double Circle::PerimeterP(int r)
{
return (r + R) * 2 * PI*PoF;
}
Circle::Circle()
{
int R = 3;
int PoF = 35;
int PoR = 20;
}
Circle::~Circle()
{
std::cout << "Present by FF" << std::endl;
}
int main()
{
int r;
Circle SwimmingPool;
std::cout << "Please input the radius of the Swimming Pool." << std::endl;
std::cin >> r;
std::cout << "The fence would cost " << SwimmingPool.PerimeterP(r) << std::endl;
std::cout << "The road would cost " << SwimmingPool.AreaP(r) << std::endl;
return 0;
}
答案 0 :(得分:4)
你有:
Circle::Circle()
{
int R = 3;
int PoF = 35;
int PoR = 20;
}
该函数创建三个函数局部变量并设置它们的值。它不会初始化类的成员。将其更改为:
Circle::Circle() : R(30), PoF(35), PoR(20) {}
始终更喜欢在初始化列表中初始化,而不是在构造函数的主体中设置值。
不,你可能不会使用:
Circle::~Circle()
{
std::cout << "The fence would cost " << SwimmingPool.PerimeterP(r) << std::endl;
std::cout << "The road would cost " << SwimmingPool.AreaP(r) << std::endl;
std::cout << "Present by FF" << std::endl;
}
SwimmingPool
是main
中的变量。它不能在析构函数中使用。此外,在析构函数中打印这些消息没有意义。它应该只是
Circle::~Circle()
{
}
答案 1 :(得分:1)
Circle::Circle() : R(3), PoF(3), PoR(3) {};
将R,PoF,PoR定义为const int
析构函数不能抛出异常,通常您希望它释放该对象获取的资源。通常不是将内容输出到stdout的最佳位置。
除非您要刷新流,否则请勿使用std::endl
。请改用'\n'
。