이 클래스에 문제가 있습니다.
목표는 주 기능을 올바르게 작동시키는 것입니다. 우리는 코드가 작동 할 수 있도록 "And"함수 객체를 구현하기로되어있었습니다. 나는 우리 솔루션의 문제점을 발견 할 수 없다.
(솔루션 시작과 끝은 코드에서 "main"함수 앞에 주석으로 표시되어 있습니다)
도와 주시겠습니까? 당신의 펑터를 만들 때
감사템플릿 및 함수 개체 - C++
#include <iostream>
#include <algorithm>
using namespace std;
class NotNull
{
public:
bool operator()(const char* str) {return str != NULL;}
};
class BeginsWith
{
char c;
public:
BeginsWith(char c) : c(c) {}
bool operator()(const char* str) {return str[0] == c;}
};
class DividesBy {
int mod;
public:
DividesBy(int mod) : mod(mod) {}
bool operator()(int n) {return n%mod == 0;}
};
//***** This is where my sulotion starts ******
template <typename Function1, typename Function2, typename T>
class AndFunction
{
Function1 f1;
Function2 f2;
public:
AndFunction(Function1 g1, Function2 g2) : f1(g1), f2(g2) {}
bool operator()(T t)
{
return (f1(t) && f2(t));
}
};
template <typename Function1, typename Function2, typename T>
AndFunction <Function1, Function2, T>
bool And(Function1 f1, Function2 f2)
{
return AndFunction<Function1, Function2, T>(f1, f2);
}
//***** This is where my sulotion ends ******
int main(int argc, char** argv)
{
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char* strings[4] = {"aba", NULL, "air", "boom"};
cout << count_if(array,array+10,And(DividesBy(2),DividesBy(4))) << endl;
// prints 2, since 4 and 8 are the only numbers which can be divided by
// both 2 and 4.
cout << count_if(strings,strings+4,And(NotNull(),BeginsWith('a'))) <<endl;
// prints 2, since only "aba" and "air" are both not NULL and begin
// with the character 'a'.
return 0;
}
정확히 작동하지 않는 기능은 무엇입니까? 내가 이상한 점은 연산자 bool에서 함수를 전달한다는 것입니다. – codymanix
몇 가지주의 사항 : 1. Functors는 보통'std :: unary_function'과'std :: binary_function'을 상속 받거나'first_argument_type','second_argument_type','result_type' typedef를 정의합니다. 기능. 2. 반복자 이외의 클래스 객체는 보통 const 참조에 의해 전달됩니다. 3.'operator()'는 보통 const입니다. 4. 문자 리터럴은 상수 객체이며, char * 로의 변환은 권장하지 않습니다. 5. 펑터 'NotNull','BeginsWith' 및 DivideBy는 일반적인 것일 수 있습니다. – Philipp