c++学习笔记--book类的小结

本文通过一个简单的Book类实例介绍了C++中友元函数的应用及复制构造函数的实现方式。同时展示了如何使用成员函数进行数据操作,并通过友元函数获取类中的私有成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用这个book类简单总结了之前关于友元,内敛,复制构造函数<iomanip>

注释写了注意事项


#include<iostream>

#include<iomanip>

using namespace std;


class book{
private:
    double price;
    int date;
public:
    book():price(0),date(0){};
    book(double p,int d){price = p;date=d;};
    book(book& b){price = b.price;date = b.date;}
    ~book(){};//如果要手动写析构函数 一定要写完函数体
    void setdate(int d);
    void setprice(double p);
    int getdate();
    double getprice();
    friend void getanotherdate(book& b);//friend关键字写在返回值之前
    double getantherprice();
};//不要漏了分号 养成好习惯

void book::setdate(int d){//不要漏了作用域
    date = d;
}
void book::setprice(double p){
    price = p;
}
int book::getdate(){
    return date;
}
double book::getprice(){
    return price;
}

void getanotherdate(book& b){
    setfill(' ');
    cout<<setw(5)<<b.date<<endl;
}

inline double book::getantherprice()
{
    return price;
}

int main()
{    
    setfill(' ');
    book b1;
    cout<<"date:"<<b1.getdate()<<"  date:"<<setw(3)<<b1.getprice()<<endl;

    book b2(10,20);
    cout<<"date:"<<b2.getdate()<<"  date:"<<setw(3)<<b2.getprice()<<endl;

    book b3;
    b3.setdate(20);
    b3.setprice(60.0);
    cout<<"date:"<<b3.getdate()<<"  date:"<<setw(3)<<b3.getprice()<<endl;
    
    book b4(b3);
    cout<<"date:"<<b4.getdate()<<"  date:"<<setw(3)<<b4.getprice()<<endl;
    cout<<"date:";
    getanotherdate(b4);
    cout<<"price:"<<b4.getantherprice()<<endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值