2017-03-17 2 views
0

클래스 할당 중 하나 인 경우 다항식 클래스를 구현해야했습니다. 다항식의 계수를 저장하고 해답을 출력합니다. 되어친구 연산자의 변수 범위

std::ostream& operator << (std::ostream& out, Polynomial& p) { 
    double ans = 0; 

    for(int i = 0; i <= p.order; ++i) 
     ans += (double)p.coefficents[i] * pow(p.x, i); 

    out << ans; 

    return out; 
} 

내 주요 기능 (내 강사에 의해 작성) : 내 클래스 정의에서

, 나는 기능 출력 친구 연산자가 있습니다

friend std::ostream& operator << (std::ostream& out, Polynomial& p); 

를 다음과 같이 내 구현은 :

int main() 
{ 
    Polynomial p1 (0.5,3); // Invokes two argument constructor for p1 
    p1.inputCoefficients(); // Set the coefficient of polynomial p1 
    cout << "Polynomial p1 evaluates to " << p1 << endl; 
    Polynomial p2(p1), p3; // Copy constructor for p2 and default constructor for p3 
    cout << "Polynomial p2 evaluates to " << p2 << endl; 
    cout << "Polynomial p3 evaluates to " << p3 << endl; 
    p3 = p2; // Copy assignment operator 
    return 0; 

} 

내 질문 : 내 프로그램을 실행할 때 나는이 해당 라인을 변경하는 경우

올바른 출력 하지만
Polynomial p1 evaluates to 1.375 
Polynomial p2 evaluates to 1.375 
Polynomial p3 evaluates to 0 
Polynomial destroyed! 
Polynomial destroyed! 
Polynomial destroyed! 

: 코드의 자신의 라인 :

double ans = 0; 

내 출력이 있습니다

double ans; 

예기치 않은 일들로 시작 발생 :

Polynomial p1 evaluates to 1.375 
Polynomial p2 evaluates to 1.375 
Polynomial p3 evaluates to 1.375 
Polynomial destroyed! 
Polynomial destroyed! 
Polynomial destroyed! 

p3이 1.375로 평가되는 이유는 무엇입니까? p3는 기본 생성자를 사용하여 생성되었으므로 0을 출력하지 않습니까?

다항식이 출력 되 자마자 ans의 범위가 죽지 않습니까? 그렇지 않은 경우 또는 ans이 마지막으로 실행 한 값을 유지 한 경우 << 연산자가 두 번 실행 되었기 때문에 p2가 두 배가되지 않습니다 (2.75가되는)? 기술을 얻고 조언을 제공하는 것이 좋습니다. 궁금 해서요. 실제로 진행되고있는 일의 내부를 알고 싶습니다. 다음 초기

ans += (double)p.coefficents[i] * pow(p.x, i); 

당신이 ans0으로 초기화하지 않는 경우 : 귀하의 << 기능은 줄이 포함

/* 
Using dynamic arrays, implement a polynomial class. In mathematics, polynomial is a function of the form f(x) = a0*x^0 + a1*x^1 + a2*x^2 + a3*x^3 + ....n terms. Here, a0, a1, a2 etc. are the coefficients of the polynomial and n is the order of the polynomial. 


The private variables include the value of x (a real number), the order of the polynomial (an integer) and the dynamic array that stores the coefficients (real numbers). 

The public methods include 

a. default constructor that sets the value of x to zero and the order to 0, 
b. a two argument constructor that takes as arguments the value of x and the order of the polynomial. The values of the coefficients are set to zero. 
c. inputCoefficients(): prompts the user to input the value of the coefficients of the polynomial. For this homework, skip the user input. Instead assign the coefficent values equal to the index of the position in the array. For example, a0 = 0, a1 = 1, a2 = 2 and so on depending on the order of the particular polynomial object 
c. a copy constructor 
d. << operator overloaded that returns the value of the polynomial (obtained by evaluating the polynomial). 
e. == overloaded (copy assignment operator) 
f. destructor. Deallocates dynamic arrays and prints a message "Polynomial destroyed! " 

Below is the testing program - 
*/ 

#include <iostream> 
using std::cin; 
using std::endl; 
using std::cout; 
#include <cmath> 

class Polynomial { 
public: 
    Polynomial() { 
     x = 0, 
     order = 0; 
     coefficents = new double[order + 1]; 
    } 

    Polynomial(const double x, const int order) { 
     this->x = x; 
     this->order = order; 

     this->coefficents = new double[order + 1]; 

     for(int i = 0; i <= order; ++i) 
      this->coefficents[i] = 0; 
    } 

    Polynomial(const Polynomial& p) { 
     this->x = p.x; 
     this->order = p.order; 

     this->coefficents = new double[this->order]; 

     for(int i = 0; i <= this->order; ++i) 
      this->coefficents[i] = p.coefficents[i]; 
    } 

    ~Polynomial() { 
     std::cout << "Polynomial destroyed! " << std::endl; 
     delete[] coefficents; 
    } 

    void inputCoefficients() { 
     /* 
     for(auto& num: coefficents) { 
      std::cout << "Enter the next coefficent:: "; 
      std::cin >> num; 
     } 
     std::cout << "Thank you" << std::endl; 
     */ 
     for(int i = 0; i <= order; ++i) { 
      coefficents[i] = i; 
     } 
    } 

    Polynomial& operator = (const Polynomial& p) { 
     this->x = p.x; 
     this->order = p.order; 

     delete[] this->coefficents; 

     this->coefficents = new double[order + 1]; 

     for(int i = 0; i <= this->order; ++i) 
      this->coefficents[i] = p.coefficents[i]; 

     return *this; 
    } 

    friend std::ostream& operator << (std::ostream& out, Polynomial& p); 
    friend bool operator == (const Polynomial& p1, const Polynomial& p2); 

private: 
    double x; 
    double* coefficents; 
    int order; 
}; 

std::ostream& operator << (std::ostream& out, Polynomial& p) { 
    double ans; 

    for(int i = 0; i <= p.order; ++i) 
     ans += (double)p.coefficents[i] * pow(p.x, i); 

    out << ans; 

    return out; 
} 

bool operator == (const Polynomial& p1, const Polynomial& p2) { 
    if((p1.x != p2.x) && (p1.order != p2.order)) 
     return false; 

    for(int i = 0; i < p1.order; ++i) { 
     if(p1.coefficents[i] != p2.coefficents[i]) 
      return false; 
    } 

    return true; 
} 



int main() 
{ 
    Polynomial p1 (0.5,3); // Invokes two argument constructor for p1 
    p1.inputCoefficients(); // Set the coefficient of polynomial p1 
    cout << "Polynomial p1 evaluates to " << p1 << endl; 
    Polynomial p2(p1), p3; // Copy constructor for p2 and default constructor for p3 
    cout << "Polynomial p2 evaluates to " << p2 << endl; 
    cout << "Polynomial p3 evaluates to " << p3 << endl; 
    p3 = p2; // Copy assignment operator 
    return 0; 

} 

답변

0

: 여기

는 (참조) 내 코드의 전체입니다 ans의 값은 불확실합니다. 그런 다음 각 용어를 여기에 추가합니다. 그래서 당신은 임의의 결과를 얻습니다.

귀하의 경우, ans은 분명히 이전 호출에서 그 값을 유지하고 있습니다. p3은 빈 다항식이므로 루프는 아무 것도 추가하지 않으므로 이전 결과를 인쇄합니다.

+0

그건 내가 생각한거야. 그러나'ans'가 이전 호출에서 그 가치를 지킨다면'p2'에 대한 호출은 2.75가되지 않을 것입니다 (단지'p1' 호출 값에 계속 추가됩니다)? 'p3'에 대한 호출도 2.75가됩니까? – Aryan

+0

다른 일들이 있기 때문에 의지 할 수 없습니다. 따라서 어떤 경우에는 덮어 쓸 수도 있고 그렇지 않은 경우에는 덮어 쓸 수도 있습니다. – Barmar

+0

그건 의미가 있습니다. 그것은 무작위로 일어난 일입니다. 다음에 실행/컴파일 할 때 완전히 다른 대답이 표시 될 수 있습니까? – Aryan