Re: same object share same static variable???
This is a MIME GnuPG-signed message. If you see this text, it means that
your E-mail or Usenet software does not support MIME signed messages.
The Internet standard for MIME PGP messages, RFC 2015, was published in 1996.
To open this message correctly you will need to install E-mail or Usenet
software that supports modern Internet standards.
--=_mimegpg-commodore.email-scan.com-7042-1251931471-0001
Content-Type: text/plain; format=flowed; charset="US-ASCII"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
Mug writes:
hi, i have a strange problem on c++, can anyone explique to me:
here i have a class:
----------------------------------myclass.h--------------------
#ifndef MYCLASS_H
#define MYCLASS_H
#include <iostream>
class myclass
{
public:
myclass();
~myclass();
};
#endif
----------------------------myclass.cpp----------------------
#include "myclass.h"
myclass::myclass()
{
static bool cool=false;
if(!cool)
{
std::cout<<"hello world\n";
cool=true;
}
}
myclass::~myclass()
{
}
int main()
{
myclass *m1=new myclass();
myclass *m2=new myclass();
delete m1;
delete m2;
return 0;
}
the output of the program is quite intrigue me,
it print out just once "hello world", yet m1 and m2 are
two objects defferent, they are in defferent memory zone,for what
reason
they share the same static variable "static bool cool" ??
The objects do not share any static variables.
Your static variable is within the scope of a single function. This would be
the same as:
void function()
{
static bool cool=false;
if(!cool)
{
std::cout<<"hello world\n";
cool=true;
}
}
int main()
{
function();
function();
return 0;
}
Obviously, here you'll get the output only once, despite that function()
gets called twice.
Your code does exactly the same thing.
--=_mimegpg-commodore.email-scan.com-7042-1251931471-0001
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEABECAAYFAkqe9U8ACgkQx9p3GYHlUOK7EACfXBTwRG9e+tE55VeDoBJpFIA7
yXsAniTHr3WsSBDs+9Gya3War4Snz1Np
=2aC/
-----END PGP SIGNATURE-----
--=_mimegpg-commodore.email-scan.com-7042-1251931471-0001--