子函数调用父函数

时间:2012-11-13 03:22:16

标签: c++

我在努力让儿童功能发挥作用时遇到了困难:

.h文件

class Parent {
    int id;
    public:
        virtual int getid();
} 

class Child : public Parent {
    int id;
    public:
        int getid();
}

.cc文件

Parent::Parent( int num ) {
    id = num;
}

int Parent::getid() {
    cout << "Parent!"; 
    return id;
}

Child::Child( int num ) : Parent(num) {
    id = num;
}

int Child::getid() {
    cout << "Child!";
    return id;
}

当我Child kid = Child(0);并致电kid.getid();时,我会Parent!而不是Child!

我的实施有什么问题?

2 个答案:

答案 0 :(得分:1)

我没有看到您的问题,只需最少的修复,就会打印出Child!

http://ideone.com/zR3wTm

答案 1 :(得分:0)

您的代码中存在很多语法错误。我甚至无法编译。这里有一些注意事项。这段代码确实输出了“Child!”

#include <iostream>

class Parent {
    protected:
        //Don't redeclare id in child -- have it protected if you want child
        //to have access to it.
        int id;
    public:
        //The constructor must be delcared the same way as other member functions
        Parent(int num);
        virtual int getid();
};

class Child : public Parent {
    public:
        //Once again, the constructor must be declared
        Child(int num);
        int getid();
};

//Initializer lists should be used when possible
Parent::Parent( int num ) : id(num) {
    //id = num;
}

int Parent::getid() {
    std::cout << "Parent!"; 
    return id;
}

//Just call the Parent constructor -- no need to assign inside of the child constructor
Child::Child( int num ) : Parent(num)
{ }

int Child::getid() {
    std::cout << "Child!";
    return id;
}

int main(int argc, char** argv)
{

    Child kid(5);
    std::cout << kid.getid() << std::endl;

    return 0;

}