我試圖建立一個基本的字符串類,就像在STL中定義的一樣,但是有一個方法來處理拆分操作。下面是代碼:g ++錯誤:作用域操作符(::)的無效使用
//The header file "splitstring.h" for the interface
class ISplittable
{
public:
virtual std::vector<std::string> &split(char delim, bool rep = false) = 0;
};
class SplitString : public std::string, public ISplittable
{
public:
SplitString() : std::string() {}
SplitString(char *str) : std::string(str) {}
std::vector<std::string> &split(char delim, bool rep = false);
private:
std::vector<std::string> fields;
};
//The CPP file that provides the implementantion
#include "splitstring.h"
#include <string>
#include <vector>
std::vector<std::string> &SplitString::split(char delim, bool rep)
{
if(!fields.empty()) fields.clear(); //clear the vector if it's needed.
std::string work = this->data(); //save the original string in a temp variable.
std::string buf = ""; //buf serves as an accumulator to work with each token separately.
int i = 0;
while(i < work.length()) { //split the original string into tokens and pushes them back in the vector.
if(work[i] != delim)
buf += work[i];
else if(rep == 1) {
fields.push_back(buf);
buf = "";
} else if(buf.length() > 0) {
fields.push_back(buf);
buf = "";
}
i++;
}
if(!buf.empty())
fields.push_back(buf);
return fields;
}
的ISplittable接口提供分裂方法,它接受一個定界符(其中一個字符串應該被分割的字符)和一個布爾參數,該參數指定在分割操作應重複多次;默認代表自變量設置爲虛假。
的SplitString類從STL 串類和ISplittable接口繼承。它實現了拆分方法,已在中定義了拆分。它也有一個字段屬性其類型爲串的矢量,並且它用於存儲在分割操作之後已經獲得每個標記:該矢量的參考,然後由返回分裂方法。
在的main.cpp文件我只是嘗試創建SplitString類的一個實例,並調用它分裂方法:
//The main.cpp file
#include "splitstring.h"
#include <iostream>
using namespace std;
int main()
{
SplitString str = "Lorem ipsum dolor sit amet";
cout << str << endl;
vector<string> fld = str.split(' '); //Splits the string at every space.
for(int i = 0; i < fld.size(); i++)
cout << fld[i] << endl;
cin.get();
return 0;
}
然而,當我嘗試編譯我的代碼,G ++告訴我:
In file splitstring.h
Invalid use of '::' (line 4)
ISO C++ forbids declaration of 'vector' with no type (line 4)
'vector' declared as a 'virtual' field (line 4)
expected ';' before '<' token (line 4)
expected class-name before ',' token (line 7)
using-declaration of for non-member at class scope (line 13)In constructor 'SplitString::SplitString()'
expected class-name before '(' token (line 10)
In constructor 'SplitString::SplitString(char *str)'
expected class-name before '(' token (line 11)
In 'main.cpp'
class 'SplitString' has no member named 'split' (line 11)
我搜索的網站類似的問題,但沒有發現任何能滿足我的需求。 我真的不知道問題出在哪裏。從錯誤消息我猜有錯誤與範圍有關。請,如果你們中的任何人都可以告訴我這段代碼有什麼問題以及如何解決它,我將不勝感激。
如果這是你的整個'stringsplit.h'(或者是'splitstring.h',或'splistring.h'?),你錯過了一堆包括和包括後衛。 –
從錯誤信息的外觀來看,確實存在這個問題...... – JBL
您需要在頭文件中包含矢量和字符串。編譯器如何知道這些類型是什麼? – NathanOliver