请问C++里面的 std::string 可否当做类型来定义数组?
俺写了个小例子 在下面如果把string当成个类型比如 后面 注释掉的 Stack<string> B(9) ; 来构造一个堆栈类的数组 array编译通过但是运行就崩溃了 这是什么原理 请前辈指教 {:9_241:}
#include<iostream>
using namespace std ;
template <class T>
class Stack
{
private:
int size ;
int top = 0 ;
T *array ;
public :
Stack(int size)
{
this->size = size ;
array = new T ;
}
~Stack() { delete []array ; }
void push(T data) { array = data ; }
T pop()
{
top-- ;
cout<<" we get "<<array<<endl;
}
};
int main()
{
Stack<int> A(7) ;
A.push(22) ;
A.push(44) ;
A.push(66) ;
A.pop() ;
A.pop() ;
A.pop() ;
// Stack<string> B(9) ;
// B.push("string_1") ;
// B.push("string_2") ;
// B.push("string_3") ;
// B.pop();
// B.pop();
// B.pop();
Stack<char> C(10) ;
C.push('a') ;
C.push('b') ;
C.push('c') ;
C.pop() ;
C.pop() ;
C.pop() ;
}
可以 仰望天上的光 发表于 2014-11-22 16:17
可以
请教老大 string 可是大小不定的啊 这要在 ansi C 里面可就麻烦了吧 {:9_239:}
#include<iostream>
#include <string>
using namespace std ;
template <class T>
class Stack
{
private:
int size ;
//int top = 0 ;
int top;
T *array ;
public :
//Stack(int size)
Stack(int size):top(0)
{
this->size = size ;
array = new T ;
}
~Stack() { delete []array ; }
void push(T data) { array = data ; }
T pop()
{
top-- ;
cout<<" we get "<<array<<endl;
return array;
}
};
int main()
{
Stack<int> A(7) ;
A.push(22) ;
A.push(44) ;
A.push(66) ;
A.pop() ;
A.pop() ;
A.pop() ;
Stack<string> B(9) ;
B.push("string_1") ;
B.push("string_2") ;
B.push("string_3") ;
B.pop();
B.pop();
B.pop();
Stack<char> C(10) ;
C.push('a') ;
C.push('b') ;
C.push('c') ;
C.pop() ;
C.pop() ;
C.pop() ;
}
页:
[1]