C++ C++;stl错误,因为缺少常量

C++ C++;stl错误,因为缺少常量,c++,stl,constants,C++,Stl,Constants,我刚刚改正了一个错误,但我不明白为什么。这是康斯特。 正确的版本: #include<iostream> template <typename T> T square(T x) { return x*x; } template <typename T> class BoVector{ T arr[1000]; int size; public: BoVector():size(0){} void push(T x) {

我刚刚改正了一个错误,但我不明白为什么。这是康斯特。 正确的版本:

#include<iostream>
template <typename T>
T square(T x)
{
    return x*x;
}

template <typename T>
class BoVector{
    T arr[1000];
    int size;
public:
    BoVector():size(0){}
    void push(T x) {arr[size]=x;size++;}
    T get(int i) const {return arr[i];}
    int getSize() const {return size;}
    void print() const {for (int i=0; i< size; i++) std::cout << arr[i] << std::endl;}
};

template<typename T>
BoVector<T> operator*(const BoVector<T>& rhs1, const BoVector<T>& rhs2){
    BoVector<T> ret;
    for(int i=0; i<rhs1.getSize(); i++){
        ret.push(rhs1.get(i) * rhs2.get(i));
    }
    return ret;
}

int main()
{
//std::cout << square<int>(5) << std::endl;
BoVector<int> bv;
bv.push(2);
bv.push(4);
bv.push(5);
bv.push(100);
//bv.print();
BoVector<int> bv2;
bv2=square(bv);
bv2.print();
}
#包括
模板
T平方(T x)
{
返回x*x;
}
模板
类向量{
T arr[1000];
整数大小;
公众:
BoVector():大小(0){}
无效推送(tx){arr[size]=x;size++;}
T get(int i)const{return arr[i];}
int getSize()常量{return size;}
void print()const{for(inti=0;i模板
BoVector运算符*(常量BoVector和rhs1,常量BoVector和rhs2){
BoVector ret;

对于(int i=0;i
BoVector::operator*
具有
const BoVector&
s
rhs1
rhs2
作为参数。因此,不能对其调用非
const
成员函数,即对
rhs1
rhs2
调用的所有成员函数都应该是
const
。因此,您将运行into如果
getSize()
get()
不是
const

您已经定义了使用const的运算符,则会出现错误:

BoVector<T> operator*(const BoVector<T>& rhs1, const BoVector<T>& rhs2){
BoVector运算符*(常量BoVector和rhs1,常量BoVector和rhs2){

如果在
操作符*
中对
常量
参数调用
getsize
,则必须指定此方法不会更改对象的状态。因此有必要将该方法限定为
常量
方法:一种可以安全地调用常量对象(具有常量状态的对象)的方法


最好的做法是限定每个不改变对象状态的方法,即
print
get

rhs1
rhs2
都作为常量传递,因此不能对常量对象调用非常量函数。因为不能对
const
对象调用非
const
方法为什么你会称之为可怜的左侧
rhs1
?谢谢!那么定义尽可能多的const成员函数以避免这种类型的错误是一件好事吗?我的意思是安全的,如果一个函数没有更改类的任何属性,那么我应该将其定义为const?@daydayup是的,通常任何不需要变异的成员函数该对象应标记为
const
@TheParamagneticCroissant。lol我应将其更改为lhs。谢谢!
template<typename T>
BoVector<T> operator*(const BoVector<T>& rhs1, const BoVector<T>& rhs2){
    BoVector<T> ret;
    for(int i=0; i<rhs1.getSize(); i++){
BoVector<T> operator*(const BoVector<T>& rhs1, const BoVector<T>& rhs2){
int getsize() const {…}