const修饰函数有关问题
const修饰函数问题
//头文件
#include <iostream>
#include <vector>
using namespace std;
class SpeedDataCollection
{
public:
SpeedDataCollection();
void addValue(int tempSpeed);
void display();
int averageSpeed() const;
private:
vector <int> m_speed;
};
//.cpp
#include "SpeedDataCollection.h "
SpeedDataCollection::SpeedDataCollection()
{
}
void SpeedDataCollection::addValue(int tempSpeed)
{
m_speed.push_back(tempSpeed);
}
int SpeedDataCollection::averageSpeed() const
{
int total=0;
vector <int> ::iterator iterS;
vector <int> ::iterator iterE;
iterS=m_speed.begin();//并没有改变成员的值啊,为什么有错
iterE=m_speed.end();
for(;iterS!=iterE;iterS++)
{
total=total+(*iterS);
}
return total/m_speed.size();
}
报的错: error C2440: '= ' : cannot convert from 'const int * ' to 'int * '
请高手结合这个例子给小弟说说type function()const类型的用法。
------解决方案--------------------
vector的begin有两个成员成员函数:
iterator vector <type> ::begin()
const_iterator vector <type> ::begin() const
因为你的函数是const修饰的,所以调用的是第二个,这样就返回一个const_iterator了,所以有三种办法解决,任选其一:
1、vector <int> ::const_iterator iterS; //调用第二个函数begin() const
2、iterS=(int*)m_speed.begin(); //调用第二个函数
3、iterS=((SpeedDataCollection*)this)-> m_speed.begin(); //调用第一个函数begin()
//头文件
#include <iostream>
#include <vector>
using namespace std;
class SpeedDataCollection
{
public:
SpeedDataCollection();
void addValue(int tempSpeed);
void display();
int averageSpeed() const;
private:
vector <int> m_speed;
};
//.cpp
#include "SpeedDataCollection.h "
SpeedDataCollection::SpeedDataCollection()
{
}
void SpeedDataCollection::addValue(int tempSpeed)
{
m_speed.push_back(tempSpeed);
}
int SpeedDataCollection::averageSpeed() const
{
int total=0;
vector <int> ::iterator iterS;
vector <int> ::iterator iterE;
iterS=m_speed.begin();//并没有改变成员的值啊,为什么有错
iterE=m_speed.end();
for(;iterS!=iterE;iterS++)
{
total=total+(*iterS);
}
return total/m_speed.size();
}
报的错: error C2440: '= ' : cannot convert from 'const int * ' to 'int * '
请高手结合这个例子给小弟说说type function()const类型的用法。
------解决方案--------------------
vector的begin有两个成员成员函数:
iterator vector <type> ::begin()
const_iterator vector <type> ::begin() const
因为你的函数是const修饰的,所以调用的是第二个,这样就返回一个const_iterator了,所以有三种办法解决,任选其一:
1、vector <int> ::const_iterator iterS; //调用第二个函数begin() const
2、iterS=(int*)m_speed.begin(); //调用第二个函数
3、iterS=((SpeedDataCollection*)this)-> m_speed.begin(); //调用第一个函数begin()