저는 스스로 C + +를 스스로 가르치려고합니다. 그리고 다시 한 번 뭔가 붙어있어 고칠 수없는 것 같습니다. 당신이 보려고하는 코드의 끔찍한 혼란을 용서하십시오. 이것은 또한이 사이트의 첫 번째 게시물이기 때문에 게시물의 형식도 아마 미안합니다.템플릿을 사용하여 벡터를 만들려고 시도합니다.
두 개의 파일이 있습니다 MAIN.CPP 및 vect1.h (NO vect1.cpp 그것은 단지 헤더 파일에 교제에 같은 템플릿을 보이기 때문에)
MAIN.CPP :
#include <iostream>
#include "vect1.H"
using namespace std;
int main(){
vect1<int> inst1(10);
inst1[9]=4;
cout<<inst1[9]<<endl;
//-----
vect1<double> inst2(10);
inst2[5]=5.112;
cout<<inst2[5]<<endl;
//-----
//====PART 2=====//
cout<<"--------"<<endl;
inst2[9]=999;
cout<<inst2[9]<<endl;
//inst2.pop();
inst2.push(2);
cout<<inst2[9]<<endl;
cout<<inst2[10]<<endl;//New block
system("PAUSE");
return 0;}
vect1.h :
#ifndef VECT1_H
#define VECT1_H
#include <iostream> //DEBUG
template <class T>
class vect1{
private:
T *ptr;
T total; //work on this
int units;
int counter;
public:
//vect1();
vect1(T);
vect1();
T &operator[](const int &);
void pop();
void push(T);
};
//---------------------
/*
template <class T>
vect1<T>::vect1(){
ptr = new int [0];
}
*/
template <class T>
vect1<T>::vect1(T number){
ptr = new T [number];
total=0;
units=(int)number;
for(counter=0;counter<number;counter++){
ptr[counter]=0;
}
}
/* now the destruct is giving me errors...
template <class T>
vect1<T>::~vect1(){
total=0;
delete[] ptr;
}*/ //<<this line tosses a C2039 error
template <class T>
T &vect1<T>::operator[](const int & ref){
if(ref>0 && ref<(units)){
return ptr[ref];
}else{
throw "Error! Out of range!"; //<<make catch
}
}
//--------
template <class T>
void vect1<T>::pop(){
units = (units-1);
T *tempPtr;
tempPtr = new T[units];
for(counter=0;counter<units;counter++){
tempPtr[counter]=ptr[counter];
}
delete[] ptr;
ptr = new T[units];
for(counter=0;counter<units;counter++){
ptr[counter]=tempPtr[counter];
}
delete[] tempPtr;
}
//--
template <class T>
void vect1<T>::push(T pushnum){
units++;
const int newsize=(int)units; //<<<<<
T *tempPtr;
tempPtr = new T[units];
for(counter=0;counter<(units-1);counter++){
tempPtr[counter]=ptr[counter];
}
//tempPtr[(int)units]=pushnum;
delete[] ptr;
std::cout<<units<<std::endl;//<<DEBUG
ptr = new T[units];
for(counter=0;counter<(units-1);counter++){
ptr[counter]=tempPtr[counter];
//ptr[9]=101;
}
ptr[newsize]=pushnum; /* <<bleh */
//ptr[newsize]=12321; //DEBUG //<<Even this isn't working...
delete[] tempPtr;
}
//---------------------
#endif
,369 (콘솔에서)
출력 :
4
5.112
--------
999
11
999
-6.27744e+066
Press any key to continue . . .
계획은 당신이) (팝업 때 그래서 T의 새로운 임시 배열을 생성하고 마지막 블록을 제외한 모든 것을 복사 할 수 있도록하는 것입니다 원래 배열에서 임시 배열로, 원래 배열을 삭제 한 다음 이전 배열보다 작은 한 배열을 새로 만들고 모든 배열을 삭제하여 임시 배열을 삭제하십시오. 푸시 (숫자)에 대한 동일한 생각, 반대 방향 만. 푸시는 자체를 임시로 복사하고, 푸시는 자체를 삭제 한 다음 크기가 1 크기로 다시 생성 한 다음 임시의 모든 것을 푸시하고 임시 삭제합니다. 그런 다음 밀어 넣기로 전송 된 번호를 새 블록으로 보냅니다. 따라서이 프로그램은 두 번째 "999"라인 다음에 '2'를 출력해야합니다. 하지만 대신 "-6.27744e + 066"이 나옵니다.
Pop()이 작동하는 것 같습니다. 정렬. 하지만 푸시 (num)와 함께 진짜 문제가 있습니다. 나는 또한 갑자기 내 소멸자로부터 C2039 오류를 얻는 것 같다. 그것은 이전에 그렇게하지 않았고, 아직 그것에 어떤 변화도 일으키지 않았습니다.
누군가가이 난장판을 살펴보고 해결해야 할 부분에 대한 조언을 주시면 감사하겠습니다. 감사!
제 컴파일러로 Visual Studio 2010을 사용합니다.
이
내 빌드 로그 (일부 좋은 오류/경고와 함께 그것으로 이동합니다!)되어있다const int newsize=(int)units;
ptr = new T[units];
...
ptr[newsize]=pushnum;
, 당신은 할당 : 내가 발견
1>------ Rebuild All started: Project: chapter 16-5, Configuration: Debug Win32 ------
1>Build started 2/9/2012 5:34:01 PM.
1>_PrepareForClean:
1> Deleting file "Debug\chapter 16-5.lastbuildstate".
1>InitializeBuildStatus:
1> Creating "Debug\chapter 16-5.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1> main.cpp
1>e:\programming(cpp)\chapter 16-5\chapter 16-5\vect1.h(31): warning C4244: 'initializing' : conversion from 'double' to 'unsigned int', possible loss of data
1> e:\programming(cpp)\chapter 16-5\chapter 16-5\vect1.h(30) : while compiling class template member function 'vect1<T>::vect1(T)'
1> with
1> [
1> T=double
1> ]
1> e:\programming(cpp)\chapter 16-5\chapter 16-5\main.cpp(11) : see reference to class template instantiation 'vect1<T>' being compiled
1> with
1> [
1> T=double
1> ]
1>Manifest:
1> Deleting file "Debug\chapter 16-5.exe.embed.manifest".
1>LinkEmbedManifest:
1> chapter 16-5.vcxproj -> E:\Programming(CPP)\chapter 16-5\Debug\chapter 16-5.exe
1>FinalizeBuildStatus:
1> Deleting file "Debug\chapter 16-5.unsuccessfulbuild".
1> Touching "Debug\chapter 16-5.lastbuildstate".
1>
1>Build succeeded.
1>
1>Time Elapsed 00:00:10.62
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========
'std :: vector '의 소스를보세요. 사용자 정의 벡터를 구현할 때 많은 트랩이 있습니다 (거의 항상 예외 안전과 관련됩니다). 더 나은 방법은 * std :: vector를 * 사용하는 법을 배우는 것입니다. –
기본 벡터가 "#include"과 함께 오는 것을 의미합니까? 이전에이 코드를 사용했지만 실제로 코드를 살펴 보지 않았습니다. 내가 그렇게 생각하지 않았다는 것을 믿을 수 없다. 감사! –
Natriacid