简体   繁体   English

cpp文件中的C ++继承函数

[英]C++ inherited function in cpp file

Topic is a base class with a method called possibleEvaluationQuestions() declared in Topic . Topic是一个基类,具有在Topic声明的一种possibleEvaluationQuestions()的方法( possibleEvaluationQuestions()Topic possibleEvaluationQuestions() AlgebraTopic is a subclass of Topic . AlgebraTopicTopic的子类。 In AlgebraTopic 's cpp file I've declared the function: AlgebraTopic的cpp文件中,我声明了该函数:

vector<EvaluationQuestion *> AlgebraTopic::possibleEvaluationQuestions()
{
    return vector<EvaluationQuestion *>();
}

But get the warning "out-of-line definition..” in Xcode. It says 'possibleEvaluationQuestions()' isn't declared in AlgebraTopic , which it isn't, but, it is declared in the superclass Topic . What am I doing wrong? 但是在Xcode中得到警告“行外定义...”。它说'possibleEvaluationQuestions()'不是在AlgebraTopic声明的,它不是,而是在超类Topic声明的。做错了吗?

When you define : 当您定义时:

vector<EvaluationQuestion *> AlgebraTopic::possibleEvaluationQuestions()

The compiler is looking for the corresponding declaration : in C++ you can't define a member function without having it declared. 编译器正在寻找相应的声明:在C ++中,如果没有声明成员函数,则无法定义它。

The declaration of the base class function is the declaration of another, different function : both exist for any AlgebraTopic object. 基类函数的声明是另一个不同函数的声明:任何AlgebraTopic对象都存在。

You can convince yourself with this : 您可以这样说服自己:

struct X
{
    virtual void foo() { std::cout << "base\n"; }   
};

struct Y : X
{
    void foo() { std::cout << "derived\n"; }
};

int main(){

    Y y;
    y.foo();
    y.X::foo();
}

Output: 输出:

derived 派生

base 基础

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM