-
February 23rd, 2004, 12:07 PM
#1
Can I convert int to CString in an initialization list?
An abstract base class constructor is declared as
Base::Base(CString name);
The derived class constructor takes an integer as its parameter. This needs to be converted to, e.g., "Node 15" if the integer is 15, and used in the base class constructor.
In the base class you can only set the name in the constructor (unless I modify it). So I believe I have to use an initialization list to do this - I can't call the base class constructor from within the derived class constructor. But I can't see how to do this.
Derived::Derived(int nodeNum) : Base(?????) { }
I need something like
CString name;
name.Format("Node %d", nodeNum);
in there somewhere, but I can't for the life of me see how to do it. Sorry if this is an obvious question. I'm very familiar with C, but new to C++.
-
February 23rd, 2004, 01:09 PM
#2
Using std::string:
Code:
#include <string>
#include <strstream>
template <typename T>
std::string ToString(T& val)
{
std::ostrstream strm;
strm << "Node " << val << std::ends;
return strm.str();
}
class Base
{
public:
Base(std::string s) { }
};
class Derived : public Base
{
public:
Derived(int n) : Base(ToString(n)) { }
};
Using MFC CString:
Code:
#include <afxtempl.h>
CString ToString(int val)
{
CString name;
name.Format("Node %d", val);
return name;
}
class Base
{
public:
Base(CString s) { }
};
class Derived : public Base
{
public:
Derived(int n) : Base(ToString(n)) { }
};
Basically, all you need is a function that returns a string and use it as the argument to Base in the initialization list.
Regards,
Paul McKenzie
-
February 24th, 2004, 04:01 AM
#3
Thanks for your help. I had hoped I could do it without introducing yet another function. (C++ seems to love having a plethora of 3-line functions...)
Anyway, that works and solves the problem, so thanks!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|