使用not2时,struct vs class作为STL仿函数

GBB*_*BBL 4 c++ struct stl class

Studing STL我写了一个简单的程序来测试仿函数和修饰符.我的问题是关于使用CLASS或STRUCT编写仿函数并尝试使用函数适配器对其进行操作的差异.据我所知,在C++中,CLASS和STRUCT之间的区别在于,在最后一种情况下,成员默认是公共的.这也是我在本网站的答案中多次阅读的内容.所以请解释一下,为什么这段简短的代码无法编译,即使我在尝试使用not2修饰符时声明所有成员(只是函数重载())公开.(我还没有尝试过其他修饰符,例如粘合剂)

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;

template <class T>
void print  (T  i) {
    cout << " " << i;
}
// In the manual I read:
// "In C++, a structure is the same as a class except that its members are public by default."
//  So if I declare all members public it should work....

template <class T>
class mystruct : binary_function<T ,T ,bool> {
    public :
    bool operator() (T  i,T  j) const { return i<j; }
};

template <class T>
class generatore 
{
public:
    generatore (T  start = 0, T  stp = 1) : current(start), step(stp)
    { }
    T  operator() () { return current+=step; }
private:
    T  current;
    T  step;
};

int main () {
    vector<int> first(10);
    generate(first.begin(), first.end(), generatore<int>(10,10) );
    first.resize(first.size()*2);
    generate(first.begin()+first.size()/2, first.end(), generatore<int>(1,17) );
    cout << "\nfirst :";
    for_each (first.begin(), first.end(), print<int>);
    cout << "\nFORWARD SORT :";
    sort(first.begin(),first.end(),mystruct<int>());       // OK ! even with CLASS
    for_each (first.begin(), first.end(), print<int>);
    sort(first.begin(),first.end(),not2(mystruct<int>())); // <--- THIS LINE WILL NOT COMPILE IF I USE CLASS INSTEAD OF STRUCT
    cout << "\nBACKWARD SORT :";
    for_each (first.begin(), first.end(), print<int>);
    cout << endl;
}
Run Code Online (Sandbox Code Playgroud)

如果我使用Everithing按预期运行:

struct  mystruct : binary_function<T ,T ,bool> {
    public :
    bool operator() (T  i,T  j) const { return i<j; }
};
Run Code Online (Sandbox Code Playgroud)

我获得的部分错误消息是:

g ++ struct.cpp
/usr/include/c++/4.2.1/bits/stl_function.h:
在'std :: binary_negate>'的实例化中:
struct.cpp:52:从这里实例化
/usr/include/c++/4.2. 1/bits/stl_function.h:116:
错误:'typedef int std :: binary_function :: first_argument_type'无法访问
/usr/include/c++/4.2.1/bits/stl_function.h:338:
错误:在此上下文中
/usr/include/c ++/4.2.1/bits/stl_function.h:119:
错误:'typedef int std :: binary_function :: second_argument_type'无法访问....

似乎至少在这种情况下,结构不等同于具有公共成员的类,但为什么呢?

Meh*_*ari 11

您从其他答案中读取的差异是正确的.struct只是默认情况下class具有public辅助功能.这包括继承修饰符.基本上,public当您使用a class来使这些定义等效时,您应该在基类名称之前提及:

template <class T>
class mystruct : public binary_function<T ,T ,bool> {
    public:
    bool operator() (T  i,T  j) const { return i<j; }
};
Run Code Online (Sandbox Code Playgroud)

否则,编译器将假定它mystruct是私有继承的binary_function<T,T,bool>.

您可以通过更改struct为:来验证此事实:

struct  mystruct : private binary_function<T ,T ,bool> {
    public: // not required here
    bool operator() (T  i,T  j) const { return i<j; }
};
Run Code Online (Sandbox Code Playgroud)

这相当于您当前的定义,class并看到编译器发出类似的错误消息.