C 成员功能
C++ Member Functions
我正在尝试编写一个记录日期的简单程序。该程序使用称为日期的结构。结构内是参数化的构造函数日期。构造函数还确保日期大致有效(确保月份在1到12之间,并且天数在1-31之间(。后来的分配解决了此类验证的问题。
在结构内也是一个add_day函数。这是我遇到问题的地方。我似乎无法将struct变量称为函数以添加一天。
struct Date
{
int y, m, d;
public:
Date(int y, int m, int d);
void add_day(int n);
int month()
{
return m;
}
int day()
{
return d;
}
int year()
{
return y;
}
};
/// main program calls the struct and add day function with parameters.
int main()
{
Date today(1978, 6, 26);
today.add_day(1);
keep_window_open();
return 0;
}
// Function definition for the Constructor. Checks values to make sure they
are dates and then returns them.
Date::Date(int y, int m, int d)
{
if ((m < 1) || (m > 12))
cout << "Invalid Monthn";
if ((d < 1) || (d > 31))
cout << "Invalid Dayn";
else
y = y;
m = m;
d = d;
cout << "The date is " << m << ',' << d << ',' << y << endl;
// This function will accept the integers to make a date
// this function will also check for a valid date
}
void Date::add_day(int n)
{
// what do I put in here that will call the variables in Date to be
// modified to add one to day or d.
};
您可以通过命名,例如:
来参考其成员函数中类的成员变量void Date::add_day(int n)
{
d += n;
}
在这里,d
将参考您在摘要上声明的int d
成员变量:
struct Date
{
int y, m, d;
// ...
}
但是,正是成员变量的阴影可能使您感到困惑。另外,请注意,您还有其他设计问题以及可以改善代码的几种方法。看看此版本以获取一些灵感:
#include <iostream>
#include <stdexcept>
class Date
{
int year_, month_, day_;
public:
explicit Date(int year, int month, int day)
: year_(year), month_(month), day_(day)
{
if (month_ < 1 || month_ > 12)
throw std::logic_error("Invalid Month");
if (day_ < 1 || day_ > 31)
throw std::logic_error("Invalid Day");
}
void add_days(int days) { /* ... */ }
int year() const { return year_; }
int month() const { return month_; }
int day() const { return day_; }
};
std::ostream & operator<<(std::ostream & os, const Date & date)
{
return os << date.year() << '-' << date.month() << '-' << date.day();
}
int main()
{
Date date(1978, 6, 26);
date.add_days(1);
std::cout << date << 'n';
return 0;
}
构件变量可以在成员函数和构造函数中通过其名称(y, m, d
(或用this
指针(this->y, this->m, this->d
(明确访问。
因此,添加一天:
void Date::add_day(int n)
{
d += n; // Modifies the 'd' member variable
// ... below here we must handle what
// happens when the number of days exceeds t
// he number of days in the particular month.
};
您在构造函数中也有问题。因为参数变量构造函数与成员变量共享相同的名称。例如:
m = m;
d = d;
使用这些作业,编译器将假设您的意思是将本地参数变量分配给本地参数变量。因此,您实际上根本没有分配成员变量任何值。一种解决方案是明确指定它们如下:
this->m = m;
this->d = d;
y
变量也是如此。
相关文章:
- 类模板的成员功能的定义在单独的TU中完全专业化
- 升压信号2将插槽传递到成员功能以断开连接
- 多次实现成员功能
- 如何定义可变参数类模板的成员模板功能
- 私有成员数据不可用于公共成员功能
- 好友功能 - 成员无法访问
- 如何启用友元类的友元功能直接在C++中访问其私有成员
- 无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?
- C++从成员类型中扣除类型的功能模板?
- 如何避免大多数成员功能相同的代码重复
- 无法访问公共功能? 没有指定成员?
- C 成员功能
- =删除用户定义的成员功能,除了构造函数,分配运算符C 11
- C 朋友课程和朋友成员功能
- C 函数调用包装器包含类成员功能作为模板参数
- 共享库中静态功能成员的破坏顺序
- 可以使用仅功能成员属性进行回调界面
- 虚拟方法与std ::功能成员变量在性能方面
- 虚拟继承和功能成员
- 指向功能成员和非成员的指针