[Dev-C++] problem with static casting (C++)
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Zheo <zh...@ho...> - 2003-08-13 23:15:26
|
I´have wrote an example to show the differences between malloc and new
(in fact, just to show that new calls constructors and malloc does not):
#include <iostream>
#include <string>
#include <cstdlib>
//Class definition
class A{
public:
A();
~A();
void setData(std::string s);
std::string getData() const;
private:
std::string data;
};
//Implementación de la clase
A::A():data("sin inicializar"){
std::cout << "Constructor de A!" << std::endl;
}
A::~A(){
std::cout << "Destructor de A!" << std::endl;
}
void A::setData(std::string s){
data = s;
}
std::string A::getData() const {
return data;
}
//Main program
int main(){
using std::cout;
using std::endl;
using std::cin;
A *ptr1, *prt2;
cout << "Creamos los objetos uno con free (prt1) y otro con delete
(ptr2)" << endl;
ptr1 = (A*) std::malloc( sizeof (*ptr1) );
prt2 = new A;
cout << "Que contiene prt1?" << endl;
//Ups!!
ptr1->setData("we");
cout << ptr1->getData() << endl;
cout << endl;
cout << "Y ptr2?" <<endl;
cout << prt2->getData() <<endl;
cout << "Ahora destruimos los objetos con free y delete" <<endl;
free(ptr1);
delete prt2;
cin.get();
}
In the line: (where ptr1 is a pointer to datatype A)
ptr1 = (A*) std::malloc( sizeof (*ptr1) );
I MUST use a C-style casting, and if I try
ptr1 = static_cast<A*> std::malloc( sizeof (*ptr1) );
The compiler gives me the following error:
example1.cpp: In function `int main()':
example1.cpp:49: parse error before `::' token
What I´m doing wrong ? According this example from The C++ Programming
Language it should work with a static casting, isn´t it?:
void f()
{
int* p = static_cast<int*>(malloc(100)) ; // new allocation used as ints
// ...
}
Thanks in advance
--
**************************************************
ICQ: 19463735
MSM: zheo_ (at) hotmail (dot) com
"Heart of men are easily corrupted"
Zheo 2003
**************************************************
|