Seite 1 von 1

not declared in this scope

Verfasst: Do Dez 03, 2020 9:44 pm
von annegret
Ich versuche mit g++ das folgende Programm zu kompilieren.
Es gibt immer Fehlermeldung complex_abs was not declared in this scope.
Kann jemand mir sagen, was ich falsch gemacht habe?
Vielen Dank.

Code: Alles auswählen

#include <cassert>
#include <iostream>
#include <cmath>
using namespace std;

class complex
{
  public:
//  Konstruktor  
    
    complex( double r = 0, double i = 0 ) : real{ r }, imag{ i } { }

//  Kopie-Konstruktor

    complex(const complex& c) : real{ c.real }, imag{ c.imag } { }
	
    friend inline double const& real_value(const complex& c) { return c.real; }
    
    friend inline double      & real_value(      complex& c) { return c.real; } 

    friend inline double const& imag_value(const complex& c) { return c.imag; }
     
    friend inline double      & imag_value(      complex& c) { return c.imag; }  
      
    friend double inline complex_abs( double c )  
    {
      return c;
    }  

    friend double inline complex_abs( complex c )  
    {
      return std::sqrt( real_value( c ) * real_value( c ) + 
                        imag_value( c ) * imag_value( c ) );
    }  

    friend std::ostream& operator<<(std::ostream&, const complex&);

  private:
    double real;
    double imag;  
};




std::ostream& operator<<(std::ostream& os, const complex& v)
{
    return os << '(' << v.real << ',' << v.imag << ")";
}
  


int main( )
{
const double pi = 3.1415926;

  complex c1{ 3.0, 5.6 };

  cout << c1 << std::endl;

  complex c2 = 9.2;
  
  cout << c2 << std::endl;
  
  complex c3 = pi * pi / 6.0;
  
  cout << c3 << std::endl;
 
  cout << complex_abs( c1 ) << std::endl;
  cout << complex_abs( c2 ) << std::endl;
  cout << complex_abs( c3 ) << std::endl;
  
  cout << complex_abs( complex { 75.0, 4.0 } ) << std::endl;     

  cout << complex_abs( 75 ) << std::endl;
  
  return 0;
  
}
Edit by Xin: Codetags eingefügt.

Re: not declared in this scope

Verfasst: Do Dez 03, 2020 10:04 pm
von Xin
Was genau stellst Du Dir denn vor, was passieren soll?

Du definierst eine Klasse complex, nicht complex_abs => complex_abs ist nicht deklariert.

PS: Ich bin schon erstaunt, dass er die Funktion per "friend inline" überhaupt in Erwägung nimmt. Der Parameter ist complex, so kommt er offenbar auf die Idee, die Funktion in der Klasse Complex zu suchen. Nimm die Funktionen raus und definiere sie außerhalb des Namensraums der Klasse. Die double-Variante hat mit complex nichts zu tun, muss also auch nicht friend sein.