cannot convert 'this' pointer from 'const class Rational' to 'class Rational &' 是什么意思

#include<iostream>

using namespace std;

class Item_base
{
public:
 Item_base( const string &book=" ni",double sales_price=0.0):isbn(book),price(sales_price){cout<<"构造函数执行"<<endl;}
 string book()  const//必须加const或者会出现错误'book' : cannot convert 'this' pointer from 'const class Item_base' to 'class Item_base &'
 {
 return isbn;
 
 }
virtual double net_price(size_t n)const
{
return n*price;
}
virtual ~Item_base(){cout<<"析构函数执行"<<endl;}
private:
 string isbn;
protected:
 double price;

};

class Bulk_item:public Item_base
{
public:
 double net_price(size_t)const;
private:
 size_t min_qty;
 double discount;


};

double Bulk_item::net_price(size_t cnt)const
{
if(cnt>=min_qty)
return cnt*(1-discount)*price;
else
return cnt*price;
}


void print_total(ostream &os, const Item_base &item,size_t n)
{
 os<<"ISBN:"<<item.book()<<"\tnumber sold: "<<n<<"\ttotal price:"<<item.net_price(n)<<endl;
}


int main()
{
Item_base A;
Bulk_item B;
print_total(cout,A,10);
print_total(cout,B,10);

}

这个程序需要加#include<string>或者会出现编译错误因为要用到 string类 要不然会出现binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<c这样的错误

(2)有关const问题   在book ()函数后面要加上const 或者会出现 

Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’ 

Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’这样的错误这是因为const对象在调用成员函数是会将this指针强制转换成const this指针,他调用成员函数是会去调用相应的const *成员函数而编译器又无法将非const*类型的成员函数转换为const*类型的成员函数所以会出现编译错误。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值