java "this" in c++
I'm in a function in java and I create a new Object passing "this" as parameter:
class AClass {
AClass(TestClass t开发者_运维知识库estClass) { }
}
class TestClass {
AClass doSomething()
{
return new AClass(this);
}
}
How to do That in C++?
Should be:
class AClass {
AClass(TestClass* testClass) { }
};
class TestClass {
AClass* doSomething()
{
return new AClass(*this);
}
};
Should I pass *this, or &this?
It depends. You're probably looking for this:
class AClass {
AClass(TestClass& testClass) { }
};
class TestClass {
AClass doSomething()
{
return AClass(*this);
}
};
To use it in C++:
TestClass testClass;
AClass aClass = testClass.doSomething();
But what are you really trying to do? Unlike Java, C++ makes the distinction between values and references explicit. You should really read a good beginner's C++ book, as James McNellis has suggested.
The distinction between values/references/pointers that C++ makes is fundamental to the language and failing to respect that will lead to disaster. Again, please pick up a C++ book.
Given the declaration you wrote
class AClass {
AClass(TestClass* testClass) { }
};
You need to pass a pointer, so you'd use this
. However, it's generally preferred in C++ to use references (especially const
references) instead of pointers, so you'd declare AClass
as:
class AClass {
AClass(const TestClass& testClass) { }
};
To which you would pass *this
.
Now, there are situations in which the pointer version is preferred. For example, if testClass
were allowed to be NULL
(you can't have null references). Or if testClass
were stored in a std::vector
or similar data structure. (You can't have arrays of references.)
精彩评论