2013-08-26 28 views
1

我被困在该类的输出成员函数上。我不知道如何创建它,只是简单地说它似乎并不工作。还有其他建议会很好。在此先感谢我被困在创建一个输出成员函数

下面的代码:

#include <iostream> 
#include <string> 
#include <vector> 


using namespace std; 

class StringSet 
{ 
    public: 
    StringSet(vector<string> str); 
    void add(string s); 
    void remove(int i); 
    void clear(); 
    int length(); 
    void output(ostream& outs); 
    private: 
    vector<string> strarr; 
}; 
StringSet::StringSet(vector<string> str) 
{ 
    for(int k =0;k<str.size();k++) 
    { 
     strarr.push_back(str[k]); 
    } 
} 
void StringSet::add(string s) 
{ 
    strarr.push_back(s); 
} 
void StringSet::remove(int i) 
{ 
    strarr.erase (strarr.begin()+(i-1)); 
} 
void StringSet::clear() 
{ 
    strarr.erase(strarr.begin(),strarr.end()); 
} 
int StringSet::length() 
{ 
    return strarr.size(); 
} 
void StringSet::output() 
{ 

} 

int main() 
{ 
    vector<string> vstr; 
    string s; 
    for(int i=0;i<10;i++) 
    { 
     cout<<"enter a string: "; 
     cin>>s; 
     vstr.push_back(s); 

    } 
    StringSet* strset=new StringSet(vstr); 
    strset.length(); 
    strset.add("hello"); 
    strset.remove(3); 
    strset.empty(); 
    return 0; 
} 
+3

看起来像家庭作业。你试过什么了? – Hrishi

+3

在main()中有趣地使用'strset'。我认为修复*编译*时间错误将是一个更高的优先级。 – WhozCraig

+0

“简单地说,它似乎并没有工作”?如果你试图编译这个呢? – 4pie0

回答

0

如果您output功能付印StringSet对象的状态,你可以实现是这样的:

#include<iterator> //std::ostream_iterator 
#include<algorithm> //std::copy 

void StringSet::output(ostream& outs) 
{ 
    std::copy(starr.begin(), starr.end(), std::ostream_iterator<string>(outs, "\n")); 
} 
+2

这应该是'ostream_iterator ' –

+0

@DaveS,非常感谢,修复了 – cpp

2

好吧,你应该先解决代码中的一些错误:

  • 你使用指向StringSet的指针,然后尝试使用.运算符而不是->访问成员函数。无论如何,你真的需要动态分配你的对象吗?

    StringSet strset(vstr); // No need to allocated dynamically your object 
    
  • 之后,您所呼叫的empty()方法,它不存在...

  • 此外,如果你留在动态分配,不要忘记释放你的记忆:

    StringSet* strset = new StringSet(vstr); 
    // ... 
    delete strset; // <- Important 
    
  • 最后,我认为你的函数输出应该在流中写入你的向量的内容,你可以这样做:

    #include <algorithm> // For std::copy 
    #include <iterator> // std::ostream_iterator 
    
    void StringSet::output(ostream& outs) 
    //      ^^^^^^^^^^^^^ don't forget the arguments during the definition 
    { 
        std::copy(strarr.begin(), strarr.end(), std::ostream_iterator<string>(outs, "\n")); 
    } 
    

HERE是固定代码的一个实例。

我建议你去了解班级的工作方式:http://www.cplusplus.com/doc/tutorial/classes/

+1

我建议[www.cppreference.com](http://en.cppreference.com/w/cpp/language/classes)为C++和标准库文档,建议和样本。 – WhozCraig

+0

@WhozCraig +1完美的建议;) –

+0

感谢您的建议,是的,它应该是动态的。 – user2420395

相关问题