初学c++,vc++6.0的用法问题,怎样加头文件

初学c++,vc++6.0的用法问题,怎样加头文件,第1张

你这个问题和重复头文件没有任何关系,因为你只有一个头文件。

问题应老枝该是你把栈对侍含银象的定义放在头文件中了,比如这样:

Stack s

头文件中应老宴该只有类的定义,而没有对象的定义;对象应该在cpp文件中定义。

#ifndef _SQSTACK1_

#define _SQSTACK1_

#include <iostream>

using namespace std

template<class ElemType>

class SqStack1

{

public:

SqStack1(int)

~SqStack1()

int Length() const

void Push(const ElemType &e)

void CreateS()

void ShowS() const

private:

ElemType *m_base

int m_top

int m_size

}

#endif

template<class ElemType> //栈的初始化 

SqStack1<ElemType>::SqStack1(int m = 0)

// m=0,假如没有大于0的参数,得到一个没长度却有地址的数组,你看多危险啊

{

m_top = 0

//你想把第一个元素浪费掉以便 *** 作吗? 如果是,和下面的CreatS的循环变量不统一

m_base = new ElemType[m]

m_size = m

}

template<class ElemType> // 析构函数 

SqStack1<ElemType>::~SqStack1()

{

if(m_base!=NULL)

delete[] m_base

}

template<class ElemType> //栈的展示 

void SqStack1<ElemType>:: ShowS() const

{

for(int i = 0i < m_top i++)

{

cout << m_base[i] << " "

}

cout<<endl

}

template<class ElemType>// 求栈的长度 迅旅

int SqStack1<ElemType>::Length() const 

{

return m_top

}

template<class ElemType> //手动添加栈的值 

void SqStack1<ElemType> :: CreateS() // 是对原来的栈元素进行覆盖还是添加?

{

for(int i = 0i < m_size i++)

// 和top不统一,top从0起冲戚,i从0开始,容易出现乱码

{

cin >> m_base[i]

m_top++ 

}

}

template<class ElemType> //入栈

void SqStack1<ElemType>::Push(const ElemType &e)

{

if(m_top>=m_size)

{

ElemType *newbase

newbase = new ElemType[m_size + 10]

for(int j 散昌陵= 0j < m_top j++)

newbase[j] = m_base[j]

// cannot convert from 'int *' to 'int',m_base后加上[j]

delete[] m_base

m_base = newbase

m_size += 10  

}

m_base[m_top++] = e

}

你这是重复定义的问题,头文件并不参加编译,所以你能通过编译,但是连接器会展开早亏头文件,这时就出问题了;

首先主函数中包含了头文件,里面定义了一些InitStack,GetTop等数据,在打开cpp文件时,又展开这个头文件,再次定义,所以出现重复定义的问题;如哪

解决办法:

增加一个头文件extern.h

将你的头文件里面的内容复制进去,只是有一点,复制进去后,将所有声明的函数 变量前加上 extern 表示在其他地方声明陆橡神了,而类和结构体不用加,因为类和结构体不存在重复定义问题;

接下来,在主函数cpp文件中包含你的头文件,在其他三个cpp文件中包含 extern.h文件


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/bake/11984361.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存