一个简单的C++,帮我调试检查一下
小弟初学C++,请各位大虾帮我看看错在哪里.我编译是问题的,但结果不是我想要的.
我只是想实现一个堆栈,能够读入我想读的double类型,并打印出来。下面是代码:
//: Stack.h
const int size = 100;
class Stack{
public:
Stack(int num = 0){};
void add( double element);
void print();
int count();
private:
double stackArray[size];
int next;
};
//: Stack.cpp
#include "Stack.h "
#include <iostream>
//Stack::Stack(int num ):next(num){}
void Stack::add(double element){
stackArray[next] = element;
std::cout < < stackArray[next] < < std::endl;
next = next + 1;
}
int Stack::count(){
std::cout < < next < < std::endl;
}
void Stack::print(){
for(int i = 0; i != next; i++){
std::cout < < stackArray[i] < < std::endl;
}
}
//: Stacktest.cpp
#include "Stack.h "
#include <iostream>
using namespace std;
int main(){
//cout < < "Please input some numbers: " < < endl;
Stack doubleStack;
int num = 0;
cout < < "Please set the \ " num\ " you want to input: " ;
cin > > num;
for(int i = 0; i != num; i++ ){
double element;
cout < < "Please input the number!: " ;
cin > > element;
doubleStack.add(element);
//doubleStack.print();
//doubleStack.count();
}
//for(int j =0; j != doubleStack.count(); j++)
doubleStack.print();
cout < < "the number of the array is: " < < doubleStack.count() < < endl;
}
谢谢各位大虾
[解决办法]
class Stack{
public:
Stack(int num = 0){};
void add( double element);
void print();
int count();
private:
double stackArray[size]; //这样定义要出错的 数组的话要求里面的大小是常数.
int next;
};
Stack::Stack(int )
你可以这样该
class Stack{
public:
Stack(int num = 0){};
void add( double element);
void print();
int count();
private:
double * stackArray;
int next;
};
Stack::Stack(int num):next(num){
stackArray=new double[num];
}
Stack::~Stack(){
delete[] stackArray;
}
这样以后你再试试