使用自定义类的对象时,所遇到的error C2662错误
//头文件shop.h
#ifndef _SHOP_H_
#define _SHOP_H_
/* class Shop */
class Shop
{
public:
Shop(const string &name = " ", const double price = 0.0): m_name(name), m_price(price)
{
}
virtual double GetTotalPrices(size_t soldNumber)
{
return (m_price * soldNumber);
}
string GetName() const
{
return m_name;
}
virtual ~Shop() {}
private:
string m_name;
protected:
double m_price;
};
#endif
//main.c
#include <iostream>
#include <string>
using namespace std;
#include "shop.h "
void PrintTotal(ostream &os, const Shop &MyShop, size_t soldNumber)
{
os < < "Shop name: " < < MyShop.GetName()
< < "\tnumber sold: " < < soldNumber
< < "\ttotal price: " < < MyShop.GetTotalPrices(soldNumber)
< < endl;
}
void main(void)
{
Shop MyShop( "LCDTV: LC37BT26 ", 9999);
PrintTotal(cout, MyShop, 5);
}
编译出现如下的错误:
:\vc6.0\study\c++\studyclass\main.cpp(21) : error C2662: 'GetTotalPrices ' : cannot convert 'this ' pointer from 'const class Shop ' to 'class Shop & ' Conversion loses qualifiers
我在函数PrintTotal里没有对Shop的对象作任何转换,不知道这个错误怎么来的。请各位大虾指点。
[解决办法]
const对象或引用上只能调用const函数,你所你的
virtual double GetTotalPrices(size_t soldNumber)
声明改为:
virtual double GetTotalPrices(size_t soldNumber) const
应该就OK了。
[解决办法]
C++ 语法:
const对象或引用上只能调用const函数
[解决办法]
C++规定!你还是买本c++ Primer认真看吧,上面几乎什么都讲了。