Pod*_*odo -3 c++ constructor class operator-overloading c++11
我有Class NumDays如下所示:
Class NumDays
{
private:
double hours;
public:
NumDays() { hours = 0.0; } //default constructor
NumDays(double hr) { hr = hours; } //initializing constructor
//Large class, nothing of importance, rest of class omitted
//overloading << operator
friend ostream &operator<<(ostream &out, NumDays a);
}
Run Code Online (Sandbox Code Playgroud)
我有NumDay.cpp 这包括:
ostream &operator<<(ostream& out, NumDays a)
{
// takes amount of hours, computes to work days
int temp = a.hours / 8;
//gives remainder of hours after full 8 hr workday.
double hrs = a.hours - (temp * 8);
//outputs
cout << fixed << setprecision(0);
out << (a.hours / 8) << " Days, " << hrs << "hours";
return out;
}
Run Code Online (Sandbox Code Playgroud)
我必须main.cpp包括:
int main()
{
// Initialized UDT object Declarations
NumDays hoursWorked_John; // Instantiate with Default Constructor
NumDays hoursWorked_Sue(36.9); // Instantiate with Initializing Cons
NumDays hoursUsed_Sue(4.5); // Instantiate with Initializing Cons
cout << "John's initial hours worked: " << hoursWorked_John << endl;
hoursWorked_John.addHours(56.78);
cout << " John's final hours worked: " << hoursWorked_John << endl;
cout << "Sue's initial hours worked: " << hoursWorked_Sue << endl;
//rest of main omitted for sake of size
Run Code Online (Sandbox Code Playgroud)
当我去运行程序的这一小部分时,这是我的控制台:
任何关于为什么苏的时间如此错误的想法,但约翰是正确的?
NumDays(double hr) { hr = hours; } //initializing constructor
Run Code Online (Sandbox Code Playgroud)
哎呦.在这里,您将成员保持hours未初始化状态并修改临时参数hr.你似乎是这个意思
NumDays(double hr) { hours = hr; }
Run Code Online (Sandbox Code Playgroud)
(或更好:)
NumDays(double hr) : hours(hr) {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |