佬求帮忙!
我的题目要求如下:
通过求三个长方柱的体积的例题来体会构造函数、复制构造函数和析构函数的调用,请编写一个基于对象的程序并按下列功能进行测试。数据成员仅包括长(length)、宽(width)、高(height)。要求用成员函数实现以下功能:
(1)使用带缺省参数的构造函数为对象初始化。
(2)可以由键盘分别输入长方柱的长宽高。
(3)计算3个长方柱的体积。
(4)输出3个长方柱的体积。
(5)类中添加拷贝构造函数和析构函数。
(6)为了更好的体会复制构造函数和析构函数的调用顺序,main函数中添加以下语句的测试。
Box box3(box2);
box1=box2.test1();
box3.test2(box2);
然后我就想顺便了解一下在类中使用指针,结果编译器触发断点,我也一直找不出哪里内存溢出或者有野指针啥的,求帮忙!代码如下:
#pragma once
#include<iostream>
#include<stdio.h>
using namespace std;
class Box
{
private:
double* length, * width, * heigh;
public:
Box(double l = 2, double w = 3, double h = 4);
Box(const Box& b);
~Box();
Box& operator=(const Box& a)
{
if (this != &a)
{
delete length;
delete width;
delete heigh;
length = NULL;
width = NULL;
heigh = NULL;
length = new double;
width = new double;
heigh = new double;
length = a.length;
width = a.width;
heigh = a.heigh;
}
return *this;
}
void get_value();
double vol_cal();
void show();
Box test1();
void test2(Box);
};
#include"volume_cal.h"
Box::Box(double l, double w, double h)
{
length = new double;
width = new double;
heigh = new double;
*length = l;
*width = w;
*heigh = h;
cout << "调用带缺省参数的构造函数" << endl;
};
Box::Box(const Box& b)
{
length = new double;
width = new double;
heigh = new double;
length = b.length;
width = b.width;
heigh = b.heigh;
cout << "调用拷贝构造函数" << endl;
};
Box::~Box()
{
delete length;
delete width;
delete heigh;
cout << "调用析构函数" << endl;
};
void Box::get_value()
{
cout << "请输入长、宽、高:" << endl;
cin >> *length >> *width >> *heigh;
}
double Box::vol_cal()
{
return (*length) * (*width) * (*heigh);
};
void Box::show()
{
cout << vol_cal() << endl;
};
Box Box::test1()
{
Box box(*length, *width, *heigh);
return(box);
};
void Box::test2(Box a)
{
length = a.length;
width = a.width;
heigh = a.heigh;
};
#include"volume_cal.h"
int main()
{
Box box1, box2(3, 6);
//box1.get_value();
//box2.get_value();
//box3.get_value();
//Box box3(box2);
box1 = box2.test1();
//box3.test2(box2);
box1.show();
box2.show();
//box3.show();
}