2016-08-13 7 views
0

나는 C++ 초보자이며 왜 내 간단한 코드가 컴파일되지 않는지 이해하지 못합니다. 첫 번째 인수에서 문자열을 응용 프로그램에 전달하여 클래스의 ifstream 객체를 인스턴스화하려고합니다.
건물은 제공하지 않습니다 : 오류 : 일치를 호출에 '(표준 : : ifstream) (CONST의 char *)'C++, ifstream 객체를 위해 string 함수를 사용하여 클래스 함수에 파일 이름 전달

헤더 :

#ifndef _SIMPLE_TEST 
#define _SIMPLE_TEST 

#include <iostream> 
#include <fstream> 
#include <string.h> 

class mytest { 
public: 
    mytest(int number); 
    bool validate_config(const std::string &s); 
private: 
    std::ifstream configFileStream; 
    int magic; 
}; 

#endif 

코드 :

#include <iostream> 
#include <fstream> 
#include <string.h> 
#include "simple.hpp" 


mytest::mytest(int number) { 
    magic = number; 
} 

bool mytest::validate_config(const std::string &s) { 
    configFileStream(s.c_str()); 
    return true; 
} 

int main(int argc, char **argv) { 
    bool check; 
    std::string configFile(argv[1]); 
    mytest DBG(17); 
    check = DBG.validate_config(configFile.c_str()); 
    if (check) { 
     return 0; 
    } 
    return -1; 
} 

빌드 오류 (콘솔에서) :

Compile src/simple.cpp 
src/simple.cpp: In member function 'bool mytest::validate_config(std::string)': 
src/simple.cpp:12:28: error: no match for call to '(std::ifstream) (const char*)' 
Makefile:23: recipe for target `_out/simple.o' failed 
make: *** [_out/simple.o] Error 1 

나는 검색하고 결과는 항상 내가

+0

['std :: ifstream'] (http://en.cppreference.com/w/cpp/io/basic_ifstream) 클래스는 당신이 호출하려고하는'operator()'함수를 가지고 있지 않습니다. 아마도''open' (http://en.cppreference.com/w/cpp/io/basic_ifstream/open) 함수를 찾고 있습니까? –

답변

3

(콘솔 출력의 잘못된 형식 죄송합니다) 문자열 클래스 c_str()을 MYTEST validate_config 방법과 방법의 출력을 전달하고 부터 일해야 벌있다 mytest::validate_config 안에 사용중인 구문이 예상 한대로 작동하지 않습니다.

configFileStream(s.c_str()); 
// tries to call 
// `std::ifstream::operator()(const char*)` 
// which does not exist 

호출 연산자가 없음을 확인하려면 ifstream on cppreference을 확인하십시오. 위의 코드 라인 ifstream::ifstream constructor (2) 다음 ifstream::operator=를 호출

configFileStream = std::ifstream(s.c_str()); 
// creates a temporary `ifstream` from `s.c_str()` 
// and assigns it to `configFileStream` 

: 새로운 하나 기존 ifstream 인스턴스를 바꾸려면


, 당신은 그것의 생성자를 호출해야합니다.

임시 번호 ifstream을 기존 항목에 할당하는 것은 C++ 11 이후에만 지원됩니다.


당신이 ifstream::open method을 사용하고 원하는 것을 달성하는 더 간단한 방법 :

configFileStream.open(s.c_str()); 

이 방법은 임시 객체를 생성하지 않습니다. 파일을 열려면

여기에 전화하려고으로
+0

@ JoachimPileborg : 감사합니다. 대답을 개선했습니다. –

+0

고마워, 나는 아주 쉽다. – IgorLopez

2

std::ifstreamoperator() (...)이없는 ...

bool mytest::validate_config(const std::string &s) { 
    configFileStream(s.c_str()); 
    return true; 
} 

, 당신은 그것을 open(...)를 호출 할 수

bool mytest::validate_config(const std::string &s) { 
    configFileStream.open(s.c_str()); 
    return true; 
}