質問

います:

MyClass mc = MyClass("Some string" << anotherString);

お答えしたことを書き直すことについて何か質問をしなければなんと言ってくれてい頂いており少し汚.その読み C++による形式のマクロ経済インラインostringstream, ることにしました利用マクロ、できないことをコンストラクタです。その答えっくする。

今、私が実際には:

MY_CLASS("Some string" << anotherString << " more string!");

このマクロ:

#include <sstream>

#define MY_CLASS(stream) \
MyClass( ( dynamic_cast<std::ostringstream &> ( \
    std::ostringstream() . seekp( 0, std::ios_base::cur ) << stream ) \
) . str() )

のMyClassのコンストラクタはstring:

MyClass::MyClass(string s) { /* ... */ }
役に立ちましたか?

解決

私はあなたの行動を取得する必要がありますどのようになど、いくつかのヒントは、でこのの質問を見てすべきだと思いますあなたが欲しいます。

この種のものは少し難しいように思えます。

他のヒント

リデザインソリューション.場合はc-torに必要な文字列で受け入れ文字列になります。
また、このと同様のケースより良いだコンストラクタを受け入れ定数参考値です。

no matching function for call to ‘MyClass(std::basic_ostream <..>&)

誤ったオペレーター<< 定義を返しますstd::basic_ostreamなstd::stringstreamオブジェクトです。昇、雨などの天候によりご利用可能

dynamic_cast< const std::stringstream& >( s << "hello" << "world" )

がチームをリードで火をおこのコード:)

ちなみ:

MyClass mc = MyClass("Some string" << anotherString);

きrewritenとして

MyClass mc("Some string" << anotherString);

あなたのコンパイルエラーが含まれているように見えます。

<iosfwd> 

クラスのヘッダーファイルではなく、あなたが含まれていない

<sstream> 

CXXファイル内でます。

<<演算子は、動的キャストを行う必要があると思いますので、のostreamを返し&、ないstreamstream&

MyClass::MyClass(ostream &stream)
{
    string myString = dynamic_cast<stringstream &>(stream.str());
}

stringstream s;
MyClass *mc = new MyClass(s << "Some string" << anotherString);

しかし、実際にそれを行うのは恐ろしいことです。このような何かを試してみてください。

class Streamer
{
stringstream stream;
public:
    template <class T>
    Streamer &operator <<(const T &object) { stream << object; return *this;}
    operator string() { return stream.str(); }
};    

class MyClass
{
public:
    MyClass(const string &s) : MyString(s) {}
    string MyString;
};

int main()
{
    MyClass myClass(Streamer() << "something" << "world");
    cout << myClass.MyString;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top