2016-04-13 2 views
1

Я довольно новичок в C++ и в настоящее время пытаюсь изучить шаблоны и как они работают. В моем задании мне предлагается создать родительский класс, базовый, который принимает 4 аргумента в шаблон. Кроме того, он должен иметь подкласс, который может печатать значения базового класса.ошибка C2248, что это за ошибка и как ее исправить?

Родительский класс получает значения, читая 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; 
} 

ответ

1
Subclass b = Subclass("test"); 

Это создает объект, а затем пытается его скопировать. Ваш класс не копируется, поэтому ошибка (также, копирование производных классов - problematic по-своему). Чтобы создать объект без копирования, используйте следующий синтаксис:

Subclass b("test"); 
+0

Простая ошибка, спасибо за указание на мою глупость! :) –

0

У вас есть std::ifstream в качестве члена, но они не-Copyable, следовательно, Hte сообщение об ошибке вы цитировали. Pre-C++ 11, идиоматический способ сделать что-то не скопированное, состоял в том, чтобы объявить его конструктор копий с помощью спецификатора частного доступа (который вы видите), чтобы никто не мог случайно его использовать. В C++ 11 ключевое слово delete является предпочтительным, и вы получите сообщение об ошибке «использование удаленной функции».

Вы должны либо:

  1. Определить конструктор копирования и копирующий оператор присваивания
  2. Не иметь не Copyable член

Я бы с (2), если я вам; спросите себя, почему вам нужно это как член, а затем найдите способ его аргументации.