C++ : problem when trying to create an instance
Still trying to get back into C++ and fumbling on differences from Java.
Can anyone tell me what's wrong here?
Test.h
#ifndef TEST_H
#define TEST_H
class开发者_如何学运维 Test {
public:
int x, y;
Test();
virtual ~Test();
protected:
private:
};
#endif // TEST_H
Test.cpp
#include "Test.h"
Test::Test() {
x = 0;
y = 28;
}
Test::~Test()
{
//dtor
}
My main app header (I'm using openFrameworks)
#ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "Test.h"
class testApp : public ofBaseApp{
public:
void setup();
[snip]
Test test_obj;
};
#endif
test_app.cpp
#include "testApp.h"
#include "Test.h"
//--------------------------------------------------------------
void testApp::setup(){
test_obj = new Test();
}
[snip]
This should be straightforward, right? Define a class Test, declare a variable of class Test (test_obj) in test_app.h and then create an instance and assign it to that variable in the test_app.cpp file.
However I'm getting this error message from the compiler in the assignment line :
error: no match for ‘operator=’ in ‘((testApp*)this)->testApp::test_obj = (operator new(12u), (<statement>, ((Test*)<anonymous>)))’
What am I doing wrong? What am I not understanding here?
You use new
with pointers in C++. It is different from Java.
Your declaration of Test test_obj
should be Test* test_obj;
However, you can declare variable simply on stack like Test test_obj;
. Doing this means that you don't have to new
the object, the constructor is automatically called and hence, object is initialized.
To expand on it a little bit more:
There are two ways of object creation in C++.
- Test test_obj;
- Test* test_obj = new Test();
First one creates an object on the stack and it is automatically destroyed (destructor is called) when object goes out of scope.
For the second one, the object is created on heap and you have to explicitly call delete
on the object to destroy it like this:
delete test_obj;
Remember, there is no automatic memory management in C++, therefore, you have to remember to delete
everything that you create with new
.
Test *p = new Test();
Get into the habit of using auto_ptr or shared_ptr or unique_ptr rather than using raw pointers in C++.
new Test()
returns a Test *
, i.e. a pointer. You cannot assign this to a Test
object. You could do test_obj = Test();
, though.
In your test_app.h, you are declaring a Test object, not a pointer to a test object. Therefore in the constructor you do not need to create a new instance of Test on the heap. The error you are getting means that you are trying to assign a Test* to a variable of Test type.
To fix your error, this line :
Test test_obj;
should have been :
Test *test_obj;
It should be either:
Test *test_obj;
//...
test_obj = new Test;
// ...
delete test_obj;
Or:
Test test_obj;
Then there's no need to release test_obj
since it's automatically done as soon as it gets out of scope.
精彩评论