c++ - 在自定义向量类中重载运算符“[]”
问题描述
我有自己的向量类并尝试重载 [] 运算符。我之前看到过类似的问题,并试图根据答案修复所有问题,但它仍然无法正常工作,并且我遇到了与之前相同的错误。哪里可能出错?在此先感谢重载:
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# - 创建数据库后在 cshtml 上显示 ViewBag 列表
- javascript - 开玩笑,如何模拟一个模拟函数返回的函数
- java - Java - 使用布尔值转换为 Lambda 以返回
- slider - 我想在底部显示 slcik 滑块下一张图片作为箭头,但不想显示上一张幻灯片
- ios - 如何在 SwiftUI 中引用外部 iOS 系统状态更新?
- java - 如何在 Spring Boot 中发送带有 json 值的多部分表单数据
- javascript - 用过时的状态对 Render 中的传递道具做出反应
- android - 带有多个项目的 recycleView 上的 Android SearchView
- java - java spring注解报错,@OneToMany和@ManyToOne关系报错
- python-3.x - 如何将 Numpy 数组的元素分配给对象的指针(另一个 Numpy 数组)?