-2

我在尝试让子功能工作时遇到困难:

.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!

我的实施有什么问题?

4

2 回答 2

1

我没有看到您的问题,只需最低限度的修复,它就会打印出来Child!

http://ideone.com/zR3wTm

于 2012-11-13T03:40:25.900 回答
0

您的代码中有很多语法错误。我什至无法编译它。在这里,它通过一些注释来修复。这段代码实际上输出“孩子!”

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

}
于 2012-11-13T03:42:04.870 回答