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

#include

using namespace std;

class Item_base
{
public:
 Item_base( const string &book=" ni",double sales_price=0.0):isbn(book),price(sales_price){cout<<"构造函数执行"<  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<<"析构函数执行"< 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:"< }


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

}

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

(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*类型的成员函数所以会出现编译错误。

复制 搜索

你可能感兴趣的:(C/C++)