C++中使用默认构造函数将对象属性设置为默认值

问题描述 投票:0回答:1

我创建了一个类事件

class Event {
    char m_event_desc[DESC_LENGTH + 1]; // description of the event 
    unsigned int m_time; // time when the event starts
    unsigned int getHour();
    unsigned int getMinute(unsigned int hour);
    unsigned int getSecond(unsigned int hour, unsigned int minute);
    
public:
    Event(); // default constructor 
    void display();
    void set(const char* address = nullptr);

};

并且想知道之间的区别

void Event::set(const char* address) {
    if (address != nullptr && address[0] != '\0') {
        // start new event and store that in the current Event object
        m_event_desc[0] = '\0';
        strcpy(m_event_desc, address);
        m_event_desc[strlen(address)] = '\0'; // put null terminator to avoid any additional value after 
        m_time = time;
    }
    else {
        Event(); // reset the state as the default value 
    }

}

void Event::set(const char* address) {
    if (address != nullptr && address[0] != '\0') {
        // start new event and store that in the current Event object
        m_event_desc[0] = '\0';
        strcpy(m_event_desc, address);
        m_event_desc[strlen(address)] = '\0'; // put null terminator to avoid any additional value after 
        m_time = time;
    }
    else {
                // reset the state as the default value 
        m_event_desc[0] = '\0';
        m_time = time;
    }

}

后者有效,但我想知道为什么前者不起作用。 如果有人能帮助我解决这个问题,我将不胜感激。

c++ default-constructor
1个回答
0
投票

前一个

Event()
创建了一个
Event
类型的临时对象,然后将其丢弃。 对当前实例没有影响
this
。所以在这种情况下我们没有看到成员变量有任何变化。

在后者中,您显式重置成员变量,以便您看到预期的更改。

© www.soinside.com 2019 - 2024. All rights reserved.