Home > Mobile >  Error: Qualified reference to 'Complex' is a constructor name rather than a type in this c
Error: Qualified reference to 'Complex' is a constructor name rather than a type in this c

Time:01-20

I just started learning C , and I don't understand why when I define my Complex class's constructor outside the class, there is a compiling error, please help!


using namespace std;

int main(int argc, const char * argv[]) {
    
    class Complex{
    private:
        double real;
        double imag;
    public:
        Complex (double r, double i);
    };
    
    Complex::Complex(double r, double i){
        real = r;
        imag = i;
    };
    

    return 0;
};

CodePudding user response:

You should move the Complex class' definition outside main() function as shown below:

#include <iostream>
class Complex{
    private:
        double real;
        double imag;
    public:
        Complex (double r, double i);
    };
    
    Complex::Complex(double r, double i){
        real = r;
        imag = i;
    };


int main(int argc, const char * argv[]) {

    return 0;
}; //unnecessary semicolon. You should remove this semicolon too

CodePudding user response:

You can apply some optimizations to make your code cleaner and more performant.

Take a look at this:

#include <iostream>


class Complex
{
private :
    double m_real;
    double m_imag;

public : // constexpr functions have a possibilty to run at compile-time
    constexpr Complex( const double real, const double imag );
    constexpr const double& getReal( ) const; // getter for m_real
    constexpr const double& getImag( ) const; // getter for m_imag
};

constexpr Complex::Complex( const double real, const double imag )
: m_real( real ), m_imag( imag ) // use a member initializer list
{
}

constexpr const double& Complex::getReal( ) const
{
    return m_real;
}

constexpr const double& Complex::getImag( ) const
{
    return m_imag;
}


int main( )
{
    constexpr Complex cmpx( 1.0, 2.0 ); // declare the object constexpr to make
                                        // it a compile-time evaluated object

    std::cout << "Real: " << cmpx.getReal( ) << " --- Imaginary: " << cmpx.getImag( ) << '\n';
}

Since this is a trivial class and it is constexpr friendly, the constexpr keyword can be used extensively throughout this class's definition.

  •  Tags:  
  • Related