![](/img/trans.png)
[英]ATL: I want to create a coclass that I can use as a parameter for a method in my class. Why can't I get this to work?
[英]Can't use string in order name a file that i want to create
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
int main(){
ofstream file;
string nameclass;
cin>>nameclass;
file.open(nameclass);
return 0;
}
The compiler says:
10 21 [Error] no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'
716 7 C:\Program Files (x86)\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.9.2\include\c++\fstream [Note] void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
716 7 C:\Program Files (x86)\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.9.2\include\c++\fstream [Note] no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const char*'
這是因為,在c++11之前,function std::ofstream::open()
期待const char *
而不是std::string
。
幸運的是, std::string
已經有一個成員 function 將字符串轉換為const char *
std::string::c_str()
。
代替:
file.open(nameclass);
和:
file.open(nameclass.c_str());
它應該工作:)
話雖這么說,如果你真的想直接傳遞一個std::string
,你必須在你的編譯選項中激活c++11支持(至少)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.