C++ 构造函数和析构函数(五)

32 篇文章 0 订阅
  1. 构造函数
    1. 构造函数 由编译器自动调用一次 无须手动调用
    2. 可以有参数  ,可以发生重载
    3. 函数名 与 类名相同
    4. 没有返回值  不用写void
  2. 析构函数
    1. 没有返回值   不用写void
    2. 函数名 与类名相同  函数名前 加 ~
    3. 不可以有参数 ,不可以发生重载
    4. 析构函数 也是由编译器自动调用一次,无须手动调用

#include <iostream>
#include<iomanip>
#include<cmath>
using namespace std;

class cone {
private:
    double r;
    double l;
public:
    cone();
    cone(int r, int l);
    //cone(const cone &p);
    void setR(double r);
    void setL(double l);
    double area();
    double volume();
    ~cone();
};

cone::cone() {
    this->l = 6;
    this->r = 3;
}

cone::cone(int r,int l) {
    this->l = l;
    this->r = r;
}


//1、编译器会给一个类 至少添加3个函数    默认构造(空实现)   析构函数(空实现)   拷贝构造(值拷贝)
//2、如果我们自己提供了 有参构造函数,编译器就不会提供默认构造函数,但是依然会提供拷贝构造函数
//3、如果我们自己提供了 拷贝构造函数,编译器就不会提供其他构造函数

//cone::cone(const cone& p) {
//    this->r = p.r;
//    this->l = p.l;
//}

cone::~cone() {
    cout << "free" << endl;
}

void cone::setR(double r) {
    this->r = r;
}
void cone::setL(double l) {
    this->l = l;
}
double cone::area() {
    return 3.1415 * this->r * this->l + this->r * this->r * 3.1415;
}
double cone::volume() {
    return 1.0 / 3.0 * pow(this->r ,2) * 3.1415 * sqrt(pow(this->l, 2) - pow(this->r, 2));
}



void test() {

    cone c2 = cone(5,6);

    //构造函数调用方法
    //cone c1;
    //cone c1(3,4);
    //cone c1 = cone();
    //cone c1 = cone(3,4);
    cone c1 = cone(c2);

    //运行结果保留小数点后三位
    cout<< setprecision(3) << fixed <<c1.area()<<endl;
    cout<< setprecision(3) << fixed <<c1.volume()<<endl;
}

int main()
{
    test();
    //test调用完后执行两次析构函数
    system("pause");
    return EXIT_SUCCESS;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值