首页 > 解决方案 > 在自定义向量类中重载运算符“[]”

问题描述

我有自己的向量类并尝试重载 [] 运算符。我之前看到过类似的问题,并试图根据答案修复所有问题,但它仍然无法正常工作,并且我遇到了与之前相同的错误。哪里可能出错?在此先感谢重载:

T& operator[](int index){
        return t[index];
}
const T& operator[](int index)const{
        return t[index];
}

我得到的错误 - 'T& myvector::operator [with T = int]' 不能被重载

整个代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <bits/stdc++.h>

using namespace std;

template<class T>
class myvector{
    private:
        T* t=new T[10];
        int index;
    public:
        myvector(){
            index=0;
        }
        ~myvector(){
        }
        T& operator[](T);
        int getSize(){
            return index;
        }
        void push_back(T value){
            index=getSize();
            t[index]=value;
            index++;
        }
        T& operator[](int index){
            return t[index];
        }
        const T& operator[](int index)const{
            return t[index];
        }
        
};
template <class T>
void swapping(T &a, T &b){  
   T temp=a;
   a=b;
   b=temp;
}
template <class T>
void bubbleSort(myvector<T>& array, int size){
   for(int i=0; i<size; i++){
      int swaps=0; 
      for(int j=0; j<size-i-1; j++){
         if(array[j]>array[j+1]){ 
            swapping(array[j], array[j+1]);
            swaps=1;
         }
      }
      if(!swaps)
         break; 
   }
}
template <class T>
void print(myvector<T> array){
    for(int i=0; i<array.getSize(); i++){
        cout<<array[i]<<endl;
    }
}
void sortStrings(vector<string>& array, int size) 
{ 
    string temp; 
    for(int j=0; j<size-1; j++) 
    { 
        for(int i=j+1; i<size; i++) 
        { 
            if(array[j]>array[i]) 
            { 
                temp=array[j]; 
                array[j]=array[i]; 
                array[i]=temp;
            } 
        } 
    } 
} 
int main(){
    //cout<<"Hello world";
    //vector<int> array;
    //int array[100];
    myvector<string> array;
    string a="";
    int i=0;
    while(1){
        cout<<"Enter string:"<<endl;
        cin>>a;
        if(a=="-"){
            break;
        }
        array.push_back(a);
        i++;
    }
    for(int i=0; i<array.getSize(); i++){
        cout<<array[i]<<endl;
    }
    myvector<int> arrayN;
    int n=1;
    i=0;
    while(1){
        cout<<"Enter number:"<<endl;
        cin>>n;
        if(n==0){
            break;
        }
        arrayN.push_back(n);
        //cout<<arrayN[i]<<endl;
        i++;
    }
    cout<<endl;
    bubbleSort(array, array.getSize());
    print(array);
    //bubbleSort(arrayN, arrayN.getSize());
    //print(arrayN);
    return 0;
}

PS。我修复了混合返回,仍然是相同的错误和问题。

标签: c++overloading

解决方案


推荐阅读