新微赢技术网

标题: [求助] 构造函数 [打印本页]

作者: 冰封シ绝恋    时间: 2009-11-3 02:47
标题: [求助] 构造函数
class sequence{
public:
bool add(int ,const string&);
bool del(int);
void output()const;
sequence(const string&);
sequence(const char*); 请指教一下这两个参数的具体意义以及这两个构造函数有什么区别
~sequence();
protected:
enum{maxsize=100};
string s[maxsize];
int last;
private:
string filename;
ifstream in;
ofstream out;
};
谢了先`~
作者: 孤独の浪子    时间: 2009-11-3 02:47
我觉得应该没什么区别
作者: 踏浪    时间: 2009-11-3 02:47
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class sequence{
public:
bool add(int ,const string&);
bool del(int);
void output()const;
sequence():last(-1){}
sequence(const char*);
~sequence();
protected:
enum{maxsize=100};
string s[maxsize];
int last;
private:
string filename;
ifstream in;
ofstream out;
};
bool sequence::add(int pos,const string& entry){
if(last==maxsize-1||pos<0||pos>last-1)
return false;
for(int i=last;i>=pos;i--)
s[i+1]=s[i];
s[pos]=entry;
last++;
return true;
}
bool sequence::del(int pos){
if(pos<0||pos>last)
return false;
for(int i=pos;i<last;i++)
s[i]=s[i+1];
last--;
return true;
}
void sequence::output() const{
for(int i=0;i<=last;i++)
cout<<i<<" "<<s[i]<<endl;
}
sequence::sequence(const char* fname){
last=-1;
filename=fname;
in.open(fname);
if(!in)
return ;
while (last<maxsize-1&&getline(in,s[last+1]))
last++;
in.close();
}
sequence::~sequence(){
if(filename=="")
return ;
out.open(filename.c_str());
for(int i=0;i<=last;i++)
out<<s[i]<<endl;
out.close();
}
class sorted:public sequence{
public:
bool adds(const string&);
sorted(){}
sorted(const char*);
protected:
void sort();
private:
using sequence::add;
};
void sorted::sort(){
string temp;
int i,j;
for(i=0;i<=last-1;i++){
temp=s[i+1];
for(i=i;j>=0;j--)
if(temp<s[j])
s[i+1]=s[j];
else
break ;
s[j+1]=temp;
}
}
bool sorted::adds(const string& entry){
int i;
for(i=0;i<=last;i++)
if(entry<=s[i])
break;
return add(i,entry);
}
sorted::sorted(const char* fname):sequence(fname){
sort();
}
int main(){
string inbuffer,where;
int wh;
sequence items("test.dat");
while(true){
cout<<"\nsequence output\n";
items.output();
cout<<"\n1*****add\n"
<<"\n2*****delete\n"
<<"\n3*****quit\n";
getline(cin,inbuffer);
if(inbuffer=="1"){
cout<<"\nitem to add:";
getline(cin,inbuffer);
cout<<"\n add to where?";
getline(cin,where);
wh=atoi(where.c_str());
if(items.add(wh,inbuffer))
cout<<"item added\n";
else
cout<<"item not added";
}
else if(inbuffer=="2"){
cout<<"where to delete:";
getline(cin,where);
wh=atoi(where.c_str());
if(items.del(wh))
cout<<"item deleted\n";
else
cout<<"item not deleted";
}
else if (inbuffer=="3")
break;
}
system("pause");
return 0;
}
有点小问题 请帮忙改正一下 谢了~~~
作者: ⊿°屵重缺銭    时间: 2009-11-3 02:47
string类与const char*的关系
string abc="abcde";
const char *t=abc.c_str();
const char *m="hijklm";

string efg=m;

编译错误更正
sorted::sorted(const char* fname):sequence(fname){
作者: 龍2132    时间: 2009-11-3 02:47
OK总算清楚了 谢了~~O~~




欢迎光临 新微赢技术网 (http://bbs.weiying.cn/) Powered by Discuz! X3.2