2012-04-21 1 views
0

я следующий кодстатическая ошибка ключевого слова в классе комплексных чисел в

#include<math.h> 
class complex 
{ 

public: 
    double getRe(); 
    double gerIm(); 
    void setRe(double value); 
    void setIm(double value); 
    explicit complex(double=0.0,double=0.0); 
    static complex fromPolar(double radius,double angle); 
    complex operator+(complex rhs); 
    complex operator-(complex rhhs); 
    complex operator*(complex rhs); 
    complex operator+(double rhs); 
    complex operator-(double rhs); 
    complex operator*(double rhs); 
    complex conjugate(); 
    double norm(); 
    complex operator/(double rhs); 
    complex operator/(complex rhs); 

private: 
    double real; 
    double img; 

}; 
complex operator+(double lhs,complex rhs); 
complex operator-(double lhs,complex rhs); 
complex operator*(double lhs,complex rhs); 
complex operator/(double lhs,complex rhs); 
complex exp(complex c); 
inline double complex::getRe(){return real;} 
inline double complex::gerIm(){ return img;} 
inline void complex::setRe(double value) { real=value;} 
inline void complex::setIm(double value) { img=value;} 
inline complex::complex(double re,double im) :real(re),img(im){} 
inline static complex complex::fromPolar(double radius,double angle){ 

    return complex(radius*cos(angle),radius*sin(angle)); 

} 
inline complex complex::operator+(complex rhs) 
{ 
    return complex(this->real+rhs.real,this->img+rhs.img); 

} 
inline complex complex::operator-(complex rhs) 
{ 
    return complex(this->real-rhs.real,this->img-rhs.img); 

} 
inline complex complex::operator*(complex rhs) 
{ 
    return complex(this->real*rhs.real-this->img*rhs.img,this->real*rhs.img+this->img*rhs.real); 

} 
inline complex complex::operator+(double rhs) 
{ 
    return complex(this->real+rhs,this->img); 

} 

inline complex complex::operator-(double rhs) 
{ 
    return complex(this->real-rhs,this->img); 

} 
inline complex complex::operator*(double rhs) 
{ 
    return complex(this->real*rhs,this->img*rhs); 

} 
inline complex complex::operator/(double rhs) 
{ 
    return complex(this->real/rhs,this->img/rhs); 

} 
inline complex complex::operator/(complex rhs) 
{ 

    return (*this)*rhs.conjugate()/rhs.norm(); 


} 

inline double complex::norm() 
{ 
return (this->real*this->real+this->img*this->img); 
} 

inline complex complex::conjugate() 
{ 

    return complex(this->real,-this->img); 
} 


inline complex operator+(double lhs,complex rhs) 
{ 
    return rhs+lhs; 
} 

inline complex operator-(double lhs,complex rhs) 
{ 
    return complex(lhs-rhs.getRe(),rhs.gerIm()); 

} 
inline complex operator*(double lhs,complex rhs) 
{ 
    rhs*lhs; 

} 

inline complex operator/(double lhs,complex rhs) 
{ 
    return rhs.conjugate()*lhs/rhs.norm(); 

} 

, но говорит, что

1>c:\users\daviti\documents\visual studio 2010\projects\complex_number\complex_number\complex.h(38): error C2724: 'complex::fromPolar' : 'static' should not be used on member functions defined at file scope 

если я удалить статическое ключевое слово, оно компилируется нормально, но я использовал это статическое ключевое слово определение класса, поэтому, если я удалю его, не будет ошибкой?

+1

Используйте 'std :: complex ' из заголовка ''. Например, ваше разделение может превышать/отменять. –

+0

В этом случае? Например, когда делитель равен 0? –

+1

Если оба операнда, например. около 10^200 (или 10^-200), результат хорошо определен, но ваш метод переполняется. См. Например. http://www.mpi-hd.mpg.de/astrophysik/HEA/internal/Numerical_Recipes/f5-4.pdf. Аналогичные замечания применяются при вычислении модуля (используйте '| x | * sqrt (1 + (y/x)^2)' if '| x |> | y |', '| y | * sqrt (1 + (x/y)^2) 'else вместо простого' sqrt (x^2 + y^2) '). Как правило, не записывайте классы комплексных чисел самостоятельно, когда в стандартной библиотеке есть совершенно хороший (работает также для матриц). –

ответ

5

static должно отображаться только в определении класса, а не там, где вы реализуете метод.

class complex 
{ 
    //...... 
    static complex fromPolar(double radius,double angle); 
    //..... 
}; 

inline complex complex::fromPolar(double radius,double angle){ 
    return complex(radius*cos(angle),radius*sin(angle)); 
} 
+0

ok я буду рассматривать его в следующий раз –

1

@ Luchian ответил на вопрос достаточно хорошо. Я обсужу альтернативу для fromPolar.

Вероятно, вы уже знаете, что вы не можете написать это:

class complex 
{ 
    //.. 
    explicit complex(double real, double imaginary); 
    explicit complex(double radius, double angle); //same as above 
}; 

Второй конструктор в основном так же, как и первый (разные имена параметров не имеет значения), так что вы не можете сделать это, поэтому вы придумали решение fromPolar.

Но тонкая проблема все еще существует даже в решении fromPolar: что представляет собой единица измерения angle параметр? Это радиан, степень или что?

Поэтому я бы предложил следующий класс, который решает обе проблемы, описанные выше, и вам больше не понадобится функция fromPolar.

class complex 
{ 
    //.. 
    explicit complex(double real, double imaginary); 
    explicit complex(double radius, Angle angle); //now it is different 
}; 

где Angle другой класс определяется как:

class Angle 
{ 
    double m_value; //always maintain this in radian 

public: 
    Angle(double value, bool isradian = true); 

    double radian(){ return m_value; } 
    double degree(){ return m_value * 180/PI; }//or maybe M_PI is the symbol 
}; 

Надежда, что делает ваш класс немного лучше.

+0

bu Мне нужен конструктор для угла Да для каждого раза, я вызываю m_value как параметр справа? –

+0

@dato: Нет, 'm_value' делается' private', поэтому вы не можете его использовать. Вы должны использовать 'angle.radian()', или если вам нужен угол в градусе (по какой-либо причине), вы можете вызвать 'angle.degree()'. – Nawaz

+0

, но я должен объявить конструктор наподобие Angle (double value): m_value (value) {} right yes? –

Смежные вопросы