Re: Problems compiling simple C++ code (also problems with std::string)
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Fri, 24 Jun 2005 18:16:26 -0400
"Susan Baker" <sbaker@xxxxxxxxxxx> wrote in message
news:d9hve0$6ka$1@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> First of all, I am having problems with std::string class as follows:
>
> 1). I wanted to initialize it to NULL so I could check later, if it
> needs to be deleted later.
First, there ain't no such thing as a NULL string, just as there is no
NULL int. A string can be empty, but there is no special value that
could be denoted as NULL
Second, std::string manages its own memory, you don't need to "delete"
it, whatever that might mean. The class will free in its destructor any
memory it might have allocated.
> 2). I can't also check for equality, as you can see in the code
> snippet above, I don't want to do anything if name is NULL (still
> using C pointer parlance here) - How do I check that variable name
> has been initialized or is not empty?
if (name.empty()) {}
> 3). Most annoying (and inexplicable to me) so far is the fact that in
> the constructor shown above, the compiler somehow, does not recognize
> the fact that the methods are "bound" to a class, and therefore,
> forbids the use of the this keyword. Here is the actual compiler
> error message: "MyClass.cpp(33): error C2228: left of '.name' must
> have class/struct/union type" - Arrgh!!. Could someone please tell me
> what I'm doing wrong?.
'this' is a pointer. You probably mean this->name and this->type . And
while we are at it, since MyClass::name is not a pointer (I assume it is
an std::string, not an std::string*), you don't allocate an intance with
new. Just do
this->name = name;
Better still, use constructor initialization list:
MyClass::MyClass(std::string name, int type) :
name(name),
type(type)
// not sure this works - consider giving different names to
parameters
{
}
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
.
- Follow-Ups:
- Re: Problems compiling simple C++ code (also problems with std::string)
- From: Susan Baker
- Re: Problems compiling simple C++ code (also problems with std::string)
- Prev by Date: Re: Problems compiling simple C++ code (also problems with std::string)
- Next by Date: Re: Compiler options and memory overheads
- Previous by thread: Re: Problems compiling simple C++ code (also problems with std::string)
- Next by thread: Re: Problems compiling simple C++ code (also problems with std::string)
- Index(es):
Relevant Pages
|