私は、次のコードを持っている:C++クラス変換は可能ですか?
class B {
public:
B(const std::string& str):m_str(str) { }
B(const B& b):m_str(b.m_str) { }
B& operator=(const B& b) { m_str = b.m_str; return *this; }
private:
std::string m_str;
};
main()
{
std::string a = "abc";
B b(a);
}
クラスBは、クライアントに属します。私はそれを変更することはできませんし、その特定の名前( "B"は単なる例です)を知らないかもしれません。私が知っていることは、コンストラクタのstd :: stringを受け入れるクライアントクラスがあることです。今私はSTDから "" メインで()の種類を変更したい::以下に定義するAに文字列、:
class A {
public:
A(const std::string& str):m_str(str) { }
A(const char *str):m_str(str) { }
A(const A& a):m_str(a.m_str) { }
A& operator=(const A& a) { m_str = a.m_str; return *this; }
private:
std::string m_str;
};
は、だから今、私は(新しいメインを持っている):
main()
{
A a = "abc";
B b(a);
}
これはそのままコンパイルできません。新しいmain()を変更せずにできることはありますか?私はクラスBを変更することはできませんし、クラスAはクラスBを決して参照するべきではありません。 ありがとう!
"新しいmain()を変更せずに"なぜですか? –