如何使用从基类继承的成员函数?

时间:2014-05-04 03:18:37

标签: c++

我有一个名为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.

我该怎么办?

整个代码

#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);
}

2 个答案:

答案 0 :(得分:2)

subtract()应该是类TimeWithDate的成员函数。您似乎将它作为非成员/静态函数。因此,this指针在该函数中不再可用。

答案 1 :(得分: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;
}