What exactly does the syntax ::~ mean in newly added class in C++ Visual Studio 2010
I have s simple question:
Situation: When I r开发者_JAVA百科ightclick Source Files folder and select Add->Class - C++ class , a class is added in a separate file *.cpp and *.h (great! This is exactly what I wanted).
Now: what does the function name
classname::~classname(void)
exactly does ?
Is it a destructor of that class called "classname" ?
I cannot find explanation of this syntax "::~" on the internet, and so I am asking here. :)
There are two different things at work here:
- The namespace delimiter operator,
::
- The destructor, which is a special function that’s always called
~classname
.
In your case, the syntax classname::~classname(void)
simply defines the class’ destructor. The ::
means that what follows belongs to the class called classname
. And what follows is just the destructor name (see above).
This is the same syntax used for all class member definitions. If your class had a function called foo
that took an int
and returned an int
, then its definition outside the class would look as follows:
int classname::foo(int)
This is exactly the same as with the destructor (except that the destructor has no return value and takes no arguments).
Yes, it's a destructor.
Note that if you're writing your own destructor in production code, you're probably doing something wrong. The exception would be if you're writing an RAII container, in which case you must also write custom copy constructor and assignment operator, or if you're just trying to learn about destructors.
// myclass.h header
class MyClass
{
public:
MyClass(); // default constructor
MyClass(const MyClass& mc); // copy constructor
~MyClass(); // destructor
};
// myclass.cpp implementation
#include "myclass.h"
MyClass::MyClass() // implementation of default constructor
{
}
MyClass::MyClass(const MyClass& mc) // implementation of copy constructor
{
}
MyClass::~MyClass() // implementation of destructor
{
}
I assume you meant
classname::~classname(void)
Where ~Classname is the destructor method for the class, classname.
:: is the scope operator ~ denotes the destructor.
Yes, the syntax classname::~classname() { /*...*/ }
defines the destructor for class classname
.
Yes, it is the destructor.
ClassName::~ClassName() - is how you begin the definition of a destructor in your YourFileName.cpp.
精彩评论