我试图了解重载 - >运算符是如何工作的.我有以下课程
class Message {
public:
Message(string message) :m_text(message) {}
void printText() {
cout << "text is " << m_text << endl;
}
string m_text;
};
class MessagePointerWrapper
{
public:
MessagePointerWrapper(string message) {
m_message = std::make_unique<Message>(message);
}
Message* operator->() {
return m_message.get();
}
std::unique_ptr<Message> m_message;
};
int main(int argc, char** argv)
{
MessagePointerWrapper messageWrapper = MessagePointerWrapper("Hello World");
messageWrapper.m_message->printText();
messageWrapper->m_text = "PQR";
messageWrapper.m_message->printText();
}
Run Code Online (Sandbox Code Playgroud)
该MessageWrapper级的->运算符重载以返回Message*.所以在主要方法中,当我调用messageWrapper->它返回的是一个Message*.通常当我有一个指针时,我需要使用->运算符或deference运算符来访问该对象.根据该逻辑,为了访问对象的m_text可用性Message …
我编写了以下代码来解释运算符new
#include <iostream>
using namespace std;
class Dog {
public:
Dog() {
cout << "Dog constructed\n";
}
//overriding the new operator of the class and explicitely doing what it internally does
void* operator new(size_t n) {
cout << "operator new overriden in Dog class called size_t n = " << n << " Sizeof(Dog) = "<< sizeof(Dog) << endl;
//Allocating the memory by calling the global operator new
void* storage = ::operator new (n);
// you can now create the …Run Code Online (Sandbox Code Playgroud)