繁体   English   中英

在C ++中如何继承父类的非成员函数,这只是在文件中定义的?

[英]In C++ how to inherit a parent class' non-member functions, which is simply defined in the file?

我有这样的代码:

class A{  // declaration is simplified
 virtual void FNC1();
};
bool compare(S s1,S s2){
    return  s1<s2; 
}
void A::FNC1(){
  iterator it;
  sort(it.begin(),it.end(),compare);
}

class B : public A{
 virtual void FNC1();
};
void B:FNC1(){
  iterator it;
  // do something different

  sort(it.begin(),it.end(),compare);
}

所以我使用类B来继承类A并覆盖函数FNC1(),但问题是,如在std :: sort()函数中,第三个变量应该是一个函数,并且这样的函数总是直接声明。 我真的想知道该怎么做才能避免复制和粘贴,并让B直接继承这个功能。 我试图将compare()函数作为A的成员函数,它不会编译:sort(it.begin(),it.end(),this-> compare);

我试图将compare函数包含在一个单独的头文件中,它说我无法声明它。 我怎样才能正确地让B继承这个功能? 因为,实际上,我有3个类都需要重用A的代码,而比较函数实际上是一个复杂的代码。

你的问题是在标题中定义了函数compare ,这意味着除了签名之外你还有它的主体。 如果在两个位置包含标头,编译器将抱怨多个定义。 您应该只在标题中包含声明,并在.cpp文件中定义。

这应该进入A的标题,让我们称之为ah

bool compare(S s1,S s2);

这应该进入a.cpp

bool compare(S s1,S s2){
    return  s1<s2; 
}

顺便说一句,只是为了清除术语,你不能继承非成员函数。 您可以在任何地方使用任何非成员函数,只要您将其声明和链接包含在其目标文件中即可。

您可以使compare函数成为基类的static成员函数,而不是使其独立:

class A{  // declaration is simplified
    virtual void FNC1();
public:
    static bool compare(const A& s1, const A& s2) {
        return ...; // The logic behind your compare function goes here
    }
};

你可以使用这样的功能:

sort(it.begin(), it.end(), A::compare);

你走在正确的轨道上。 您可以简单地重用compare函数,您不需要修改它或尝试“继承”它或任何此类事物。

以下应编译并运行,没有错误。

#include <algorithm>
#include <vector>

struct S { int i; };

class A{  // declaration is simplified
public:
 virtual void FNC1();
};
bool compare(const S& s1,const S& s2){
    return  s1.i < s2.i;
}

void A::FNC1(){
  std::vector<S> v;
  std::sort(v.begin(),v.end(),compare);
}

class B : public A{
public:
 virtual void FNC1();
};
void B::FNC1(){
  std::vector<S> v;
  // do something different

  std::sort(v.begin(),v.end(),compare);
}

int main () { A a; B b; a.FNC1(); b.FNC1(); }

如果你比较A的成员它将无法编译的原因可能是你没有公开或保护它。 默认情况下,类的成员是私有的,派生类不能看到私有成员。

你需要:

class A{  // declaration is simplified
{
    virtual void FNC1();

    protected:
        bool compare( S s1, S s2 ){...}
};

暂无
暂无

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

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