2014-05-23 2 views
0

예측 자 수정 자의 수치 해석을 쓰고 있습니다. 내 함수의 이전 값을 추적하기 위해 작동하는 순환 배열을 작성했습니다.중첩 클래스의 생성자에 템플릿 typename을 전달합니다.

#include <cmath> 
// Circular array 
// this is fixed sized container to hold the last n update of a function 
// written by Keivan Moradi 2014 
template <typename T> 
class carray 
{ 
    public: 
     carray(int s) 
     { 
      size = exp2(ceil(log2(s))); 
      array = new T[size]; 
      SizeNegOne = size-1; 
      head = SizeNegOne; 
     } 
     void initialize(T n) 
     { 
      for (head=0; head<size; head++) 
       array[head]=n; 
      head = SizeNegOne; 
     } 
     void update(T h) 
     { 
      // bitwise modulus: 
      // if "size" is in power of 2: 
      //(head+1) & SizeNegOne = (head+1) % size 
      // in contrast to modulus, this method is guaranteed to get positive values 
      head = (head+1) & SizeNegOne; 
      array[head]=h; 
     } 
     T operator[](int index) 
     { 
      // bitwise modulus: 
      // if "size" is in power of 2: 
      // (head + index) & SizeNegOne = (head + index) % size 
      // in contrast to modulus, this method is guaranteed to get positive values 
      return array[(head + index) & SizeNegOne]; 
     } 
     ~carray() 
     { 
      delete [] array; 
     } 
    protected: 
    private: 
     T *array; 
     int size, SizeNegOne, head; 
}; 

다음 코드는이 코드가 작동하도록되어 방법을 보여줍니다

지금은 그것을 이런 식으로 뭔가 사용할 수 있도록 내가 둥지에 예측 클래스 내부에이 클래스를 원하는
int main() 
{ 
    carray<float> phi(3); 
    phi.initialize(-64); 
    std::cout<<phi[0]<<" "<<phi[-1]<<" "<<phi[-2]<<" "<<phi[-3]<<" "<<phi[-4]<<" "<<phi[-5]<<" "<<phi[-6]<<" "<<phi[-7]<<" "<<phi[-8]<<std::endl<<std::endl; 

    phi.update(6.1); 
    std::cout<<phi[0]<<" "<<phi[-1]<<" "<<phi[-2]<<" "<<phi[-3]<<" "<<phi[-4]<<" "<<phi[-5]<<" "<<phi[-6]<<" "<<phi[-7]<<" "<<phi[-8]<<std::endl<<std::endl; 

    phi.update(7.1); 
    std::cout<<phi[0]<<" "<<phi[-1]<<" "<<phi[-2]<<" "<<phi[-3]<<" "<<phi[-4]<<" "<<phi[-5]<<" "<<phi[-6]<<" "<<phi[-7]<<" "<<phi[-8]<<std::endl<<std::endl; 

    phi.update(8.1); 
    std::cout<<phi[0]<<" "<<phi[-1]<<" "<<phi[-2]<<" "<<phi[-3]<<" "<<phi[-4]<<" "<<phi[-5]<<" "<<phi[-6]<<" "<<phi[-7]<<" "<<phi[-8]<<std::endl<<std::endl; 

    phi.update(9.1); 
    std::cout<<phi[0]<<" "<<phi[-1]<<" "<<phi[-2]<<" "<<phi[-3]<<" "<<phi[-4]<<" "<<phi[-5]<<" "<<phi[-6]<<" "<<phi[-7]<<" "<<phi[-8]<<std::endl<<std::endl; 

    phi.update(10.1); 
    std::cout<<phi[0]<<" "<<phi[-1]<<" "<<phi[-2]<<" "<<phi[-3]<<" "<<phi[-4]<<" "<<phi[-5]<<" "<<phi[-6]<<" "<<phi[-7]<<" "<<phi[-8]<<std::endl<<std::endl; 

    return 0; 
} 

:

#include <cmath> 
template <typename T> 
class predictor 
{ 
    public: 
     predictor(int s) 
     { 
      size = s; 
     } 
     void update(T a) 
     { 
      f.update(a); 
     } 
     T predict2ndOrder() 
     { 
      return f[0] + (3/2*(f[0]-f[-1])-1/2*(f[-1]-f[-2])); 
     } 
    private: 
     int size; 
     carray<T> f(size); 
     class carray 
     { 
      public: 
       carray(int s) 
       { 
        size = exp2(ceil(log2(s))); 
        array = new T[size]; 
        SizeNegOne = size-1; 
        head = SizeNegOne; 
       } 
       ~carray() 
       { 
        delete [] array; 
       } 
       void initialize(T n) 
       { 
        for (head=0; head<size; head++) 
         array[head]=n; 
        head = SizeNegOne; 
       } 
       void update(T h) 
       { 
        head = (head+1) & SizeNegOne; 
        array[head]=h; 
       } 
       T operator[](int index) 
       { 
        return array[(head + index) & SizeNegOne]; 
       } 
      private: 
       T *array; 
       int size, SizeNegOne, head; 
     }; 
}; 
012 :
int main() 
{ 
    predictor<float> phi(4); 
    phi.update(10); 
    phi.update(11); 
    phi.update(12); 
    phi.update(13); 
    std::cout<<phi.predict2ndOrder()<<std::endl; 
} 

이 코드는 내 실패 최선의 시도를 보여줍니다

해결 방법 알려주세요. 저는 새로운 C++ 프로그래머입니다. 그래서 쉽게 이해할 수 있습니다. ;)

+0

을 난 당신이 [세의 규칙]을 따르지 않는주의 (http://stackoverflow.com/questions/4172722/what- : 여기

는 VS2010에서 나를 위해 잘 컴파일 수정 된 코드입니다 is-the-rule-of-three). – chris

+0

[Rule of Zero] (http://isocpp.org/blog/2012/11/rule-of-zero) –

+0

과 동일하므로'std :: vector'를 사용하십시오. – Jarod42

답변

0

샘플 코드에 일부 타이핑이 있지만, T 유형을 예측에서 carray로 전송하는 것은 매우 간단합니다. 한 가지 가능성이 있습니다 : 첫 번째 코드 조각에서와 마찬가지로 carray를 템플릿 클래스로 선언하십시오. 나머지 작업을하려면 typos를 수정하고 carray 및 init 크기에 대한 클래스 정의 아래의 크기 및 f 선언을 이동하여 예측 자 생성자에서 올바른 순서로 초기화 목록을 만듭니다.

#include <cmath> 
using namespace std; 

template <typename T> 
class predictor 
{ 
public: 
    predictor(int s) 
     : size(s) 
     , f(size) 
    { 
    } 
    void update(int a) 
    { 
     f.update(a); 
    } 
    T predict2ndOrder(float deltaT) 
    { 
     return f[0] + deltaT*(3/4*(f[0]-f[1]-1/2*(f[1]-f[2]))); 
    } 
private: 
    template <typename S> 
    class carray 
    { 
    public: 
     carray(int s) 
     { 
     size = exp(ceil(log((S)s))); 
     array = new S[size]; 
     SizeNegOne = size-1; 
     head = SizeNegOne; 
     } 
     ~carray() 
     { 
     delete [] array; 
     } 
     void initialize(S n) 
     { 
     for (head=0; head<size; head++) 
      array[head]=n; 
     head = SizeNegOne; 
     } 
     void update(S h) 
     { 
     head = (head+1) & SizeNegOne; 
     array[head]=h; 
     } 
     S operator[](int index) 
     { 
     return array[(head + index) & SizeNegOne]; 
     } 
    private: 
     S *array; 
     int size, SizeNegOne, head; 
    }; 

    int size; 
    carray<T> f; 
}; 
+0

제안 된 코드를 사용해 보았습니다. 오타가 수정되었지만 여전히 코드에서 이러한 오류가 발생합니다 :: 블록 : 오류 : '클래스 T'의 선언 오류 : 섀도우 템플릿 매개 변수 '클래스 T'. Visual Studio 2013에는 오류가 없지만 출력이 없습니다. 질문이 있습니다. (T) s는 (는) 캐스팅 중 일부 kine입니까? 그것이 다른 무엇이라도 있다면, 나는 그것에 대해 더 많이 배울 수 있도록 무엇이라고 불 렸습니다. 감사합니다. – user9224

+0

@ user9224 그림자가있는 템플릿 매개 변수에 대해 사과드립니다. carray-T-template-param을 다른 것으로 변경하십시오. 당신은 주물에 관하여 맞습니다; 올바른 로그 구현을 선택하는 것이 필요하다고 생각합니다. 로그 (float)와 로그 (double) 사이. static_cast (s)은 C가 적고 C++가 더 낫습니다. 결과에 대해서, 나는 의미론을 전혀 보지 못했다는 것을 인정한다. 새 템플릿 매개 변수 이름 carray에 대한 대답을 업데이트했습니다. –

+0

@ user9224 코드 블록을 사용하지는 않지만 코드 (템플릿 매개 변수 이름에 제안 된 변경 포함)를 실행하면 VS2010에서 출력이 나오고 빈 결과가 나오는 내용을 볼 수 없습니다. phi.predict2ndOrder는 float를 반환하기 때문에 항상 std :: cout에 인쇄 할 값이 있습니다. 또한 예측 자 (predictor)는 마지막 main()에서 배열이라는 carray 멤버에 대해 initialise()를 호출하지 않습니다. 어쩌면 당신은 예측 자 생성자에서 이것을 호출하기를 원할 것입니다. –

관련 문제