【发布时间】:2014-03-07 03:45:56
【问题描述】:
我是 C++ 新手,遇到错误,我不确定为什么有人可以帮助我解决这个问题?提前致谢。
这是我的头文件。
#ifndef SSTACK_H
#define SSTACK_H
#include <cstdlib>
#include <string>
class sstack {
public:
// Constructor
sstack( int cap);
// Copy Constructor
sstack( const sstack& s );
~sstack( );
void push ( const std::string& s);
std::string& pop ();
std::string& top () const;
bool IsEmpty () const;
int size() const;
int getCapacity() const;
// NONMEMBER FUNCTIONS for the bag class
// Precondition: s1.size( ) + s2.size( ) <= s1.Capacity.
// Postcondition: The stack returned is the union of s1 and s2.
sstack operator +(const sstack& s2);
private:
int Capacity; // Capacity is the maximum number of items that a stack can hold
std::string* DynamicStack;
int used; // How many items are stored in the stack
};
#endif
这里是堆栈的 .cpp 文件我的错误在这个类中 我的第一个错误是:
sstack.cpp:14:24: 错误:'int' 之前的预期 unqualified-id
sstack.cpp:14:24: 错误:在 'int' 之前需要 ')'
我的第二个错误是:
sstack.cpp:19:24: error: 'const' 之前的预期 unqualified-id
sstack.cpp:19:24: 错误:在 'const' 之前预期 ')' 我在网上环顾四周,似乎无法弄清楚问题是什么?
顺便说一句,就像我之前说的,我是 C++ 新手,所以如果还有其他看起来不好或错误的地方或可以做得更好的地方,请告诉我,以便我学习谢谢
#include "sstack.h"
// Constructor
//ERROR HERE
sstack(int cap){
test = new std::string [cap];
Capacity = cap;
}
// Copy Constructor
//ERROR 2 HERE
sstack(const sstack& s){
test = new std::string[1000];
for(int i = s.size()-1; i > 0; i--){
test[i] = *s.pop();
}//end of for
Capacity = s.getCapacity();
used = s.size();
}
~sstack(){
delete []test;
}
void push ( const std::string& s){
test[used] = *s;
used++;
}
std::string& pop (){
used-= 1;
popped = test[used];
test[used] = "";
return *popped;
}
std::string& top () const{
top = test[used--];
return *top;
}
bool IsEmpty () const{
if(used <= 0){
return true;
}else{
return false;
}
}
int size() const{
return used;
}
int getCapacity() const{
return Capacity;
}
// NONMEMBER FUNCTIONS for the bag class
// Precondition: s1.size( ) + s2.size( ) <= s1.Capacity.
// Postcondition: The stack returned is the union of s1 and s2.
sstack operator +(const sstack& s2){
int amount = used;
if(amount + s2.size() <= Capacity){
for(int i = used + s2.size()-1; i > used; i--){
test[i] = *s2.pop();
used++;
}//end of for
}//end of if
}
int Capacity = 1000; // Capacity is the maximum number of items that a stack can hold
std::string* DynamicStack;
int used = 0; // How many items are stored in the stack
std::string test[1000];
std::string popped;
std::string top;
【问题讨论】:
-
你不应该在这里硬编码数组的大小
test = new std::string[1000]。它不会是原件的真实副本。此外,更喜欢在构造函数初始化器列表中进行初始化。真的,远离“原始”数组。看看标准集合。