C++ 在构造函数中使用结构
使用构造函数,我可以使用存储在结构向量中的信息为位于私有类中的变量设置值吗?这将构造类的值,其中一个是month monthName的字符串名称,使用月份的数字位置作为结构向量中位置的指南C++ 在构造函数中使用结构,c++,struct,constructor,C++,Struct,Constructor,使用构造函数,我可以使用存储在结构向量中的信息为位于私有类中的变量设置值吗?这将构造类的值,其中一个是month monthName的字符串名称,使用月份的数字位置作为结构向量中位置的指南 //m/d/y;year_is_private_variable Date(unsigned m, unsigned d, unsigned y){ year=y; for(unsigned i=0;i<12;++i){ if(m==yVec
//m/d/y;year_is_private_variable
Date(unsigned m, unsigned d, unsigned y){
year=y;
for(unsigned i=0;i<12;++i){
if(m==yVector.mPlace.at(i)){
monthName=yVector.mName.at(i);
}
}
您可以使用类/结构内部部分存储的值在构造时初始化其他类/结构变量。但是,您必须记住,要使用的变量应该在使用前进行初始化。 出于示例的目的,您可以使用staticconst字段来存储所有月份。简化代码如下
#include <iostream>
#include <string>
#include <vector>
struct Date
{
Date(int month)
: month_name(values[month])
{
}
std::string month_name;
private:
static const std::vector<std::string> values;
};
const std::vector<std::string> Date::values = {"may", "april"};
int main()
{
Date d = Date(1);
std::cout << d.month_name;
return 0;
}
很难理解您的意思,但您是否只是想做m==yVector.ati.mPlace和monthName=yVector.ati.mName;相反