【发布时间】:2016-04-13 16:30:13
【问题描述】:
我对 c++ 还很陌生,目前正在尝试学习模板及其工作原理。我的作业要求我创建一个父类 base,它将 4 个参数放入模板中。它还必须有一个可以打印基类值的子类。
父类通过读取txt文件获取值。
现在我正在尝试实例化一个子类,以便可以在父类中逐行打印值。
我的代码很乱,因为我对 c++ 还很陌生。我的背景包括 C#、Java 和 Javascript。任何帮助都会很棒!提前致谢。
错误信息:
Error 1 error C2248: 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream' : cannot access private member declared in class 'std::basic_ifstream<_Elem,_Traits>'
代码:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cctype>
using namespace std;
//template that accept 4 different data types
template<class Type1, class Type2, class Type3, class Type4>
class Base {
//protected declarations
protected:
Type1 str;
Type2 i;
Type3 d;
Type4 b;
//public declarations
public:
int lineRead;
int data;
string line, delimiter;
size_t pos;
ifstream inputfile;
string token;
//public functions
public:
void readFile(int lineNum) {
//temp information holders
lineRead = 0;
pos = 0;
delimiter = " ";
//open .txt file
inputfile.open("file.txt");
//while end of file is not reached
while (!inputfile.eof()) {
//increment line counter
lineRead++;
//read line
getline(inputfile,line);
//if this is the line requested fill the template members with the
//correct data. <string, int, double, bool>
if(lineNum == lineRead){
//getting the string
pos = line.find(delimiter);
token = line.substr(0, pos);
str = token;
line.erase(0, pos + delimiter.length());
//getting the integer
pos = line.find(delimiter);
token = line.substr(0, pos);
i = stoi(token);
line.erase(0, pos + delimiter.length());
//getting the double
pos = line.find(delimiter);
token = line.substr(0, pos);
d = stod(token);
line.erase(0, pos + delimiter.length());
//getting the boolean
pos = line.find(delimiter);
token = line.substr(0, pos);
b = to_bool(token);
line.erase(0, pos + delimiter.length());
}
}
//close the file
inputfile.close();
system("pause");
};
//Changes a string to lower case and then reads the string
//to find if the value is true or false. Returns a boolean.
bool to_bool(string str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
istringstream is(str);
bool tempB;
is >> boolalpha >> tempB;
return tempB;
}
};
class Subclass : public Base<string, int, double, bool> {
private:
string name;
public:
Subclass::Subclass(string name) {
cout << "test";
}
void printValues() {
cout << str;
}
};
//main function
int main() {
//call Base class and give the template data types
Subclass b = Subclass("test");
//read the file
b.readFile(2);
return 0;
}
【问题讨论】:
标签: c++ templates constructor subclass parent