弹出错误,表明类类型不提供下标运算符。
我是C ++的新手,似乎无法弄清楚这一点。如果您向我提供了一些提示以及问题之外我的代码出了哪些问题,将非常感谢。
class Transaction {
protected:
char * ime;
char smetka[16];
float iznos;
Date d;
public:
Transaction() {}
Transaction( char * ime , char * smetka ,float iznos ,Date d ) {
this->ime = new char[strlen(ime)+1];
strcpy(this->ime,ime);
strcpy(this->smetka,smetka);
this->iznos=iznos;
this->d=d;
}
Transaction(const Transaction & c) {
ime = new char[strlen(ime)+1];
strcpy(this->ime,c.ime);
strcpy(this->smetka,c.smetka);
this->iznos=c.iznos;
this->d=c.d;
}
friend ostream & operator<<(ostream & out, const Transaction & c) {
if(c.iznos>0) {
return out << "Inflow " << c.iznos << " " << c.ime << "(" << c.smetka << ")-" << c.d.getDay() << "." << c.d.getMonth() << "." << c.d.getYear() << endl;
} else {
return out << "Outflow " << c.iznos << " " << c.ime << "(" << c.smetka << ")-" << c.d.getDay() << "." << c.d.getMonth() << "." << c.d.getYear() << endl;
}
}
Transaction(char * ime, char * smetka) {
this->ime = new char[strlen(ime)+1];
strcpy(this->ime,ime);
strcpy(this->smetka,smetka);
}
};
class TransactionAccount {
private:
char * ime;
char smetka[16];
Transaction * t;
int n;
int kapacitet;
public:
TransactionAccount() {
this->t = new Transaction[3];
this->kapacitet=3;
}
TransactionAccount(char * ime,char * smetka) {
this->ime = new char[strlen(ime)+1];
strcpy(this->ime,ime);
strcpy(this->smetka,smetka);
}
void addTransaction(Transaction & a) {
if(n<kapacitet) {
this->t = &a;
} else {
kapacitet*=2;
this->t = &a;
}
}
Transaction getTransList() {
return *t;
}
int getTransCapacity() {
return this->kapacitet;
}
int getTransNumber() {
return this->n;
}
virtual ~TransactionAccount() {}
};
int main() {
char name[50],number[16];
float amount;
int d,m,y;
int n;
bool isInflow;
TransactionAccount ta;
int testcase;
cin>>testcase;
switch (testcase) {
case 1: {
cout<<"------Transaction test------"<<endl;
cin>>name;
cin>>number;
cin>>amount;
cin>>d>>m>>y;
Transaction t(name,number,amount,Date(d,m,y));
cout<<t;
}
break;
case 2: {
cout<<"------TransactionAccount test:constructor, desctuctor & get-
functions------"<<endl;
cin>>name;
cin>>number;
TransactionAccount ta(name,number);
cin>>n;
for (int j=0; j<n; j++) {
cin>>name>>number>>amount>>d>>m>>y;
Transaction t(name,number,amount,Date(d,m,y));
ta.addTransaction(t);
}
cout<<"Capacity: "<<ta.getTransCapacity()<<endl;
cout<<"Number of elements: "<<ta.getTransNumber()<<endl;
cout<<(ta.getTransList())[n]; // -- here is the
problem
cin>>n;
cout<<"The element on position "<<n<<" is "<<endl;
}
return 0;
}
我想要的结果是它调用了(该类的)前一个对象并进行打印。
答案 0 :(得分:0)
此特定问题的答案是getTransList
返回单个Transaction
(而不是顾名思义,是“列表”)。然后发生错误是因为Transaction
没有重载的下标运算符(很好;它可能不应该这样)。
Transaction getTransList() {
return *t;
}
应替换为
Transaction* getTransList() {
return t;
}
正确返回数组。
但是,提供的代码还有很多其他问题。当您尝试运行/调试代码时,其中一些将变得明显。对于其余的内容,虽然您当然可以在该站点上询问有关特定问题的(新)问题,但最好咨询您的老师。