1

非常に初歩的で単純な質問ですが、うまくいけば簡単な答えが得られます。私の問題は基本的に、次の関数パラメーターの1行のコードに帰着します。

void className::read(const string &)
{
  ifstream fin;
  fin.open(fname);
  /* ...function code */
  fin.close()
}

入力は、文字列 fname (つまりobject.read(fname)) として main で確立されます。これを行うと、このスコープで fname が宣言されていないことがわかります。したがって、私の質問は、入力である fname を fin.open() のファイル名として使用する方法です。すでに助けてくれたすべての人に感謝し、以前の問題の説明が不十分で申し訳ありません。

4

3 に答える 3

1

fname が関数パラメーターをよく参照している場合は、 const 修飾子があるため可能です。そのため、 const 修飾子を削除する必要があります。それが完了すると、他の変数に代入するのと同じようになります。

ただし、関数内で fname の値を使用する方が簡単な場合は、新しい変数を作成して割り当てるだけです。

std::string newVariable = fname;
于 2012-09-17T02:11:14.163 に答える
1

私はこれを単純化しすぎているかもしれませんが、これはあなたが望むものですか? fname?の名前付きパラメーター

void className::read(const string& fname)
{
  printf(fname.c_str()); // Do what you want with the string.
}
于 2012-09-17T02:13:33.973 に答える
1

I'm not sure I understand your question. Are you asking whether you can modify fname within the function? If that's what you want you need to modify the signature of the read function to take a non-const reference.

void className::read( string& fname )
{
  fname = "something else";  // this change is visible even after the 
                             // function returns
}

Or are you asking how to create a local string that is a copy of fname?

void className::read( const string& fname )
{
  std::string local = fname;  // local contains a copy of fname
}
于 2012-09-17T02:16:52.127 に答える