您的位置:首页 > 其它

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

2012-05-24 22:41 549 查看
#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*类型的成员函数所以会出现编译错误。

复制搜索

复制搜索
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐