我有一個名爲TimeWithDate的繼承自Date類和Time類的派生類。 我嘗試通過使用::
來使用成員函數。如何使用從基類繼承的成員函數?
這樣的:
int subtract(TimeWithDate& other_date){
return Date::subtract(other_date) + Time::subtract(other_date);
}
,但我得到了這樣的警告: Error: a nonstatic member reference must be relative to a specific object.
然後我試着這樣說:
int subtract(TimeWithDate& other_date){
return *(Date*)this.subtract(other_date) + *(Time*)this.subtract(other_date);
}
,並得到了這樣的警告: Error: 'this' may only be used inside a nonstatic member function.
w ^我應該怎麼做?
整個代碼
#include<iostream>
using namespace std;
class Time
{
int hour, second, minute;
public:
Time();
Time(int h, int m, int s);
void set(int h, int m, int s);
void increment();
void display();
bool equal(Time &other_time);
bool less_than(Time &other_time);
int subtract(Time &another);
};
class Date
{
int year, month, day;
public:
Date();
Date(int y, int m, int d);
void increment();
bool equal(Date &another);
int subtract(Time &another);
};
class TimeWithDate : public Time, public Date
{
public:
bool compare(TimeWithDate&);
void increment();
int subtract(TimeWithDate&);
};
bool TimeWithDate::compare(TimeWithDate &other_date){
if (Date::equal(other_date) && Time::equal(other_date))
return true;
else return false;
}
void TimeWithDate::increment(){
Time::increment();
Time zero(0, 0, 0);
if (Time::equal(zero))
Date::increment();
}
int subtract(TimeWithDate& other_date){
return Date::subtract(other_date) + Time::subtract(other_date);
}
'*(Date *)'是一個壞主意,請設計你的類,以便像這樣投射是沒有必要的。 –