2014-05-04 89 views
0

我有一個名爲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); 
} 
+0

'*(Date *)'是一個壞主意,請設計你的類,以便像這樣投射是沒有必要的。 –

回答

2

subtract()TimeWithDate類的成員函數。它看起來像是一個非成員/靜態函數。因此,this指針在該函數中不再可用。

+0

另外,'this'是一個指針,所以'this.'應該是'this->' –

2

你需要解析你的整個代碼,在我的電腦(VS2012)下面工作正常。

#include <iostream> 
using namespace std; 

class Base1 
{ 
public: 
    void print(const char *str){ cout << "base1 " << str << endl; } 
}; 

class Base2 
{ 
public: 
    void print(const char *str){ cout << "base2 " << str << endl; } 
}; 

class Derived : public Base1, public Base2 
{ 
public: 
    void print(const char *str); 
}; 

void Derived::print(const char *str) 
{ 
    cout << "Derived " << str << endl; 
    Base1::print(str); 
    Base2::print(str); 
} 

int main() 
{ 
    Derived d; 
    d.print("hello"); 

    return 0; 
} 
+0

-1不適用於[ideone](http://ideone.com/L24XRG):-(.. 。 –

+0

@πάνταῥεῖyes在你的鏈接中你使用了一個winapi習語:TCHAR。[試試這個](http://ideone.com/1U0G8L) – CoffeeandCode

+0

已經上傳整個代碼 – Gnostikoi