c++ - 如何在构造函数中初始化结构数据成员?
问题描述
我正在使用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;
解决方案
它们已经为默认的 coinstructor 进行了初始化(可能应该是=default
)。
然后只需使用初始化列表:
data::data(std::string loc, int year, int month):loc(std::move(loc)), year(year), month(month) {
}
也正确包含字符串:
#include <string>
推荐阅读
- java - Android - theme.xml 和 theme.xml(night)
- python - 我如何在不出错的情况下对此添加反应?
- excel - 如何摆脱 VBA 中的范围失败错误?
- mysql - mysql选择那些价格不同的项目
- java - 为什么 Collections 类中的 sort 等方法不在 List 接口中?
- ios - 线程 1:“-[_UIDatePickerIOSCompactView setHighlightsToday:]:无法识别的选择器发送到实例”
- c - C:使用在 main 函数中创建的二维数组
- javascript - 如何在 paper.js 中向这些 Ball 对象插入文本?
- php - PHP 的 date_diff() 行为异常
- python - 没有足够参数调用的 Ctypes 参数