0

我希望能够以 char* 的形式将一个常量字符串附加到另一个字符串的末尾,然后将生成的字符串用作 open() 的参数。这是它的样子:

文件1.cpp

#include "string.h"

file2 foo;

char* word = "some";
foo.firstWord = word; //I want the file2 class to be able to see "some"

文件2.h

#include <fstream>
#include <iostream>

#define SECONDWORD "file.txt"

class file2{
public:
    file2();
    static char* firstWord;
    static char* fullWord;

private:
    ofstream stream;

}

文件2.cpp

#include "file2.h"

char* file2::firstWord;
char* file2::fullWord;

fullWord = firstWord + SECONDWORD; //so fullWord is now "somefile.txt" ,I know this doesn't work, but basically I am trying to figure out this part

file2::file2(){
    stream.open(fullWord);
}

所以我不是很精通C++,所以任何帮助将不胜感激!

4

1 回答 1

1

C++ 风格的解决方案可能如下。

#include <string>

char* a = "file";
char* b = ".txt";

...

stream.open((std::string(a) + b).c_str());

这里会发生什么?首先,std::string(a)创建一个临时std::string对象。比b价值增加了​​。最后,c_str()方法返回一个包含a + b.

于 2013-07-23T17:31:13.823 回答