我正在使用一些遗留代码,我需要一个StoreStrings类存储 一些字符串,能够返回MyString *。
我试过这个:
typedef char MyString[64];
class StoreStrings{
public:
void store(MyString *aStr)
{
theVec.push_back(aStr);
}
const MyString* get(){return theVec.begin();}
private:
std::vector<MyString> theVec;
};
但我很失望,因为它不能用这种语法编译。
StoreStrings myStore;
myStore.store("Hello");//cannot convert parameter 1 from 'char [6]' to 'char (*)[64]'
我之前要实例化一个MyString。
MyString myStr = "Hello";
myStore.store(&myStr);
如何重写StoreStrings类以便拥有myStore.store(“Hello”);编制?
答案 0 :(得分:1)
我会建议类似的东西
Storestring.h
#pragma once
#include <vector>
class StoreStrings
{
public:
void store(const char* aStr)
{
pszStr = new char[64];
strcpy_s(pszStr,64,aStr);
theVec.push_back(pszStr);
};
~StoreStrings(void){
for(std::vector<char*>::iterator it = theVec.begin();it!=theVec.end();++it){
delete *it;
}
};
std::vector<char*>::iterator getBegin(){return theVec.begin();};
std::vector<char*>::iterator getEnd(){return theVec.end();};
private:
char* pszStr;
std::vector<char*> theVec;
};
main.cpp
#include "StoreStrings.h"
#include <iostream>
int main(void){
StoreStrings s;
s.store("a");
s.store("b");
s.store("c");
for(std::vector<char*>::iterator it = s.getBegin();it!=s.getEnd();++it){
std::cout << *it<<std::endl;
}
return 0;
};
答案 1 :(得分:1)
数组不能在STL容器中使用,因为它要求类型可以复制构造和可分配
您可以尝试关注,但std::string
方法最好。
typedef char MyString[64];
struct X{
MyString s;
};
class StoreStrings{
public:
void store(MyString aStr)
{
X temp ;
for(int i=0;aStr[i];++i)
temp.s[i] =*(aStr+i);
theVec.push_back(temp);
}
// Here iterator is returned.
const std::vector<X>::iterator get(){return theVec.begin();}
private:
std::vector<X> theVec;
};
int main(){
StoreStrings myStore;
MyString m ="Hello";
myStore.store(m);
}