gpt4 book ai didi

c++ - 共享的数据成员指针C++

转载 作者:行者123 更新时间:2023-12-01 14:39:11 25 4
gpt4 key购买 nike

我创建了两个类SystemClock,用于显示当前时间(通过从ctime创建指向struct tm的指针),另一个类名为CustomClock,该类从用户指定的小时,分​​钟和秒创建时间对象。
CustomClass继承自SystemClock,SystemClock具有一种显示方法,以小时:分钟:秒的格式显示时间。

由于某些原因,所有对象都共享SystemClock中的tm *字段。因为当我创建CustomClock对象时,说c1(1,2,3)和c2(4,5,6)并调用c1.display和c2.display都打印4:5:6。(请参见下面的代码为了清楚)

码:

#include <chrono>
#include <ctime>
#include <iostream>
class SystemClock {

public:
tm* time;
SystemClock() {
time_t now = std::time(0);
time = localtime(&now);
}
void display() {
std::cout << "Time: "<< this->time->tm_hour << ":";
std::cout << this->time->tm_min << ":";
std::cout << this->time->tm_sec << std::endl;
}
};

class CustomClock : public SystemClock {

public:
// CustomClock():SystemClock() {}
CustomClock(int hours, int minutes, int seconds) {
this->set_time(hours,minutes,seconds);
}
CustomClock(CustomClock &c) {
std::cout<<"inside copy constructor";
c.display();
this->set_time(c.time->tm_hour,c.time->tm_min,c.time->tm_sec);
}
void set_time(int hours, int minutes, int seconds) {
this->time->tm_hour = hours;
this->time->tm_min = minutes;
this->time->tm_sec = seconds;
}
};

int main() {
CustomClock c1(1,2,3);
CustomClock c2(4,5,6);
c2.display(); //prints Time: 4:5:6
c1.display(); //prints Time: 4:5:6 instead of 1:2:3
CustomClock c3(c1); //prints current time instead of 1:2:3
c3.display();
return 0;
}

当我通过创建值类型数据成员而不是指针类型数据成员进行上述实现时,它可以正常工作。我无法理解所有对象共享指针的方式和原因。

最佳答案

指针被剪切了,因为localtime方法正在将指针返回到内部对象。

The returned value points to an internal object...





The function also accesses and modifies a shared internal object...



您可以在 http://www.cplusplus.com/reference/ctime/localtime/上了解更多有关它的信息。

关于c++ - 共享的数据成员指针C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62447327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com