开发者

C++ class conversion possible?

I have the following code:

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);
}

class B belongs to the client. I can't change it and I may not even know its specific name ("B" is simply an example); all I know is there's a client class that accepts a std::string for i开发者_JAVA百科ts constructor. Now I want to change the type of "a" in main() from std::string to A, as defined below:

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;
};

So now I have a new main():

main()
{
    A a = "abc";
    B b(a);
}

This can't compile properly as it is. Is there anything I can do without changing the new main()? I can't change class B, and class A should not reference class B in any way. Thanks!


add an cast operator

class A {
public:
   ....
  operator const std::string()
    {
        return m_str;
    }


Add user-defined conversion function as:

class A
{
 public:
    //other code
    operator std::string()
    {
        return m_str;
    }
    //...
};

This allows you write these:

B b(a); //which is what you want
std::string s = a; //this is also okay;

void f(std::string s) {}

f(a); //a converts into std::string, by calling user-defined conversion function

However you cannot write this:

 const A ca("hi");
 std::string s = ca; //error

Its because ca is a const object which cannot invoke non-const user-defined conversion function.

Note the user-defined conversion function returns the string by value which means it returns a copy of the original string. So you may want to avoid this by defining it as:

operator const std::string &() const
{
     return m_str;
}

Now, with this you can write this:

const A ca("hi");
std::string s = ca; //ok

A a("hi");
std::string s = a; //ok


How about

int main() //note the correct declaration of main
{
    A a = "abc";
    B b(a.GetString()); //GetString returns m_str;
}

By the way, all your definitions of copy constructors and copy-assignment operators coincide with the definitions the compiler would have auto-generated for you.

Edit
I just noticed your constraint that main() should not change. In this case you can define a conversion function from A to string (but it can be dangerous, note).

class A
{
    ...
    operator std::string() const {return m_str; }
};


Add this to class A:

operator std::string () { return m_str; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜