首页 > 解决方案 > 如何在构造函数中初始化结构数据成员?

问题描述

我正在使用data.h具有以下代码的文件

#ifndef __DATA_h_INCLUDED__
#define __DATA_h_INCLUDED__

#include "string"

struct data {
    std::string location="";
    int year = 0, month = 0;

    data();
    data(std::string location, int year, int month);
};

#endif

data.cpp文件看起来像这样

#include "data.h"
#include "string"

using namespace std;

data::data() {
    //initialize the data members (location,year,month)
} 

data::data(std::string loc, int year, int month) {
    //initialize the data members (location,year,month)
}

在其他一些 .cpp 文件中,我如何获取这些值并初始化这些值。

节点.h

struct Node {
data d;

Node(std::string id, int year, int month); 

};

节点.cpp

Node::Node(string id, int year, int month){
// here i want to initialize 'data' 

}

打印.cpp

Node* node;
cout<<node->data->location;

标签: c++

解决方案


它们已经为默认的 coinstructor 进行了初始化(可能应该是=default)。

然后只需使用初始化列表:

data::data(std::string loc, int year, int month):loc(std::move(loc)), year(year), month(month) {
}

也正确包含字符串:

#include <string>

推荐阅读