简体   繁体   English

关于C ++中虚函数继承的难题

[英]Puzzle about virtual function inheritance in C++

I'm noob in C++, and I have the following header file (Header.h) 我是C ++中的noob,我有以下头文件(Header.h)

#ifndef HEADER_H
#define HEADER_H

#include <iostream>

using namespace std;

class Predicate
{
public:
    virtual void print() = 0;
};

class UnaryIntegerPredicate : public Predicate 
{
public:
    virtual void print();
};

class BiaryIntegerPredicate : public Predicate
{
public:
    virtual void print();
};

#endif

and in another separate .cpp file (Source.cpp), I tried to implement the print method, but got an "expected an expression" error. 在另一个单独的.cpp文件(Source.cpp)中,我试图实现print方法,但得到了“预期的表达式”错误。

#include "stdafx.h"
#include "Header.h"

#include <iostream>

using namespace std;

UnaryIntegerPredicate::UnaryIntegerPredicate() : Predicate()
{
    virtual void print()
    {
        cout << "int : boolean" << endl;
    }
}

what is wrong here, thanks! 这里有什么不对,谢谢!

I see you are probably coming from a Java background. 我发现你可能来自Java背景。 What you need is 你需要的是什么

void UnaryIntegerPredicate::print()
{
    cout << "int : boolean" << endl;
}

You don't need the stuff surrounding that. 你不需要那些东西。 Since you have already declared in your header that UnaryIntegerPredicate derives from Predicate , you don't mention that again in the implementation file. 由于您已在头文件中声明UnaryIntegerPredicate派生自Predicate ,因此您不会在实现文件中再次提及它。 You show that the print method that you are writing is the print method of the UnaryIntegerPredicate class by prefixing the name of the method with the name of the class as I have shown above. 通过在方法名称前加上上面显示的类名称,可以显示正在编写的print方法是UnaryIntegerPredicate类的print方法。

You also don't need the virtual keyword in the cpp file because that is already specified in the header file. 您也不需要cpp文件中的virtual关键字,因为已在头文件中指定了该关键字。

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

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