超载新操作员

Overloading the new operator

本文关键字:操作员 超载      更新时间:2023-10-16

我在班上过载操作员'new'有问题。

代码:

time.h

#ifndef TIME_H_
#define TIME_H_
#include <cstddef>
#include <stdlib.h>
class Time {
private:
    int hours;
    int minutes;
public:
    Time(int a = 0, int b = 0) : hours(a), minutes(b) {};
    void AddMin(int m);
    void AddHours(int h);
    void Reset(int h = 0, int m = 0);
    void Show() const;
    Time Suma(const Time & t) const;

    //przeladowania
    void* operator new(size_t);
};
#endif

time.cpp

 #include "time.h"
#include <iostream>
#include <cstddef>
#include <stdlib.h>
void Time::AddMin(int m)
{
    this->minutes += m;
    this->hours += this->minutes / 60;
    this->minutes += this->minutes % 60;
}
void Time::AddHours(int h)
{
    this->hours += h;
}
void Time::Reset(int h, int m)
{
    this->hours = h;
    this->minutes = m;
}
void Time::Show() const
{
    std::cout << this->hours << " hours and " << this->minutes << " minutes" << std::endl;
}
////overloading
void* Time::operator new(size_t size)
{
    void *storage = malloc(size);
    if (NULL == storage) {
        throw "allocation fail : no free memory";
    }
    std::cout << storage << std::endl;
    Time * time = (Time*)storage;
    time->minutes = 12;
    return time;
}

prog.cpp

#include <iostream>
#include "time.h"
int main()
{
    Time * timeNew = new Time();
    timeNew->Show();
    std::cout << timeNew << std::endl;
    return 0;
}

和结果 - addreses:

0104F5E8
0 hours and 0 minutes
0104F5E8

我不明白为什么我的对象在内存中还具有其他地址。我认为,如果我返回指针,所以我的对象timenew(in prog.cpp)应该具有与储存时间相同的adress.cpp。

i Konw这是一个函数,但我使用了指针,因此返回程序后不应删除。

为什么Timenew有0小时0分钟?我在功能中签名值。

你能解释一下我做错了什么吗?

注释:正如讲故事的人在评论中指出的那样,在称为构造函数之前访问对象通常是一种非常糟糕的做法,并且可能容易容易出现危险的错误。这几乎从来没有必要。除非您故意实施肮脏的黑客,否则您可能不应该这样做。请记住,C 中的新运算符与您在Python中可能发现的新运营商完全不同,以创建不变的类型。

为什么Timenew有0小时0分钟?我在新功能中分配一个值。

发生这种情况是因为在运算符new之后,构造函数被调用,并且由于没有参数,因此构造函数将在将12分配给minutes后重置minutehours的值。

如果您想在operator new中查看此作业的效果,只需更改:

 Time(int a = 0, int b = 0) : hours(a), minutes(b) {};

with:

 Time(int a, int b) : hours(a), minutes(b) {};
 Time() {};