我想创建一个C ++类的复数。这是Complex.h
(最基本的形式)
#ifndef _COMPLEX
#define _COMPLEX
#include "TVector2.h"
class Complex : public TVector2{
public:
Complex(double re, double im): TVector2(re,im){;}
protected:
double m_re;
double m_im;
};
#endif
这里是main.cpp
#include "Complex.h"
#include "TVector2.h"
int main() {
Complex c;
}
这是我正在使用的Makefile
CC = g++
CFLAGS = -g -Wall
CFLAGSROOT = `root-config --cflags`
LIBSROOT = `root-config --glibs`
all: Main
Complex.o: Complex.cpp
$(CC) $(CFLAGS) -c Complex.cpp $(CFLAGSROOT)
Main: main.cpp Complex.o
$(CC) $(CFLAGS) -o Main main.cpp Complex.cpp $(CFLAGSROOT) $(LIBSROOT)
clean:
rm *.o
我收到此错误:
main.cpp: In function ‘int main()’:
main.cpp:9:11: error: no matching function for call to ‘Complex::Complex()’
Complex c;
^
以及这些注意事项:
In file included from main.cpp:2:0:
Complex.h:16:2: note: candidate: Complex::Complex(double, double)
Complex(double re, double im): TVector2(re,im), m_re(re), m_im(im){;}
^~~~~~~
Complex.h:16:2: note: candidate expects 2 arguments, 0 provided
Complex.h:13:7: note: candidate: Complex::Complex(const Complex&)
class Complex : public TVector2{
^~~~~~~
Complex.h:13:7: note: candidate expects 1 argument, 0 provided
Complex.h:13:7: note: candidate: Complex::Complex(Complex&&)
Complex.h:13:7: note: candidate expects 1 argument, 0 provided
Makefile:13: recipe for target 'Main' failed
make: *** [Main] Error 1
答案 0 :(得分:2)
在编写Complex c;
时,您试图调用Complex::Complex ()
类中未定义的构造函数Complex
,因为唯一可用的构造函数带有2个参数Complex::Complex (double, double)
。 / p>
因此,有两种方法可以解决此问题:
只需提供构造函数参数:
Complex c (0, 0);
如果提供构造函数参数看起来过于庞大,则可以只提供一个默认构造函数,为您做同样的事情:
class Complex : public TVector2 {
public:
Complex (double re, double im): TVector2 (re, im) {}
Complex (): TVector2 (0, 0) {}
protected:
double m_re;
double m_im;
};
或者,如果您至少使用C ++-11:
class Complex : public TVector2 {
public:
Complex (double re, double im): TVector2 (re, im) {}
Complex (): Complex (0, 0) {}
protected:
double m_re;
double m_im;
};
那将允许您编写Complex c;
。
但是,如果您想编写Complex c (5);
,除了im
之外,它会初始化0 Complex c;
部分,则可以将那些构造函数参数标记为可选:
class Complex : public TVector2 {
public:
Complex (double re = 0, double im = 0): TVector2 (re, im) {}
protected:
double m_re;
double m_im;
};
注意:我不同意TVector2
中的表示复数的继承概念,因为继承表示“ is-a”关系,而且我认为复数不是向量(此类向量包含几种方法)这对于复数没有意义,并且缺少复数,而确实如此)。即使这样,您的m_re
和m_im
成员也不会初始化,并且包含不确定的值,使用该值将导致不确定的行为。
请记住并进行更改,以使其不继承自TVector2
,因此其代码段将更改为:
(2):
class Complex {
public:
Complex (): m_re (0), m_im (0) {}
Complex (double re, double im): m_re (re), m_im (im) {}
protected:
double m_re;
double m_im;
};
或(如果您至少使用C ++-11):
class Complex {
public:
Complex (double re, double im): m_re (re), m_im (im) {}
Complex (): Complex (0, 0) {}
protected:
double m_re;
double m_im;
};
(3):
class Complex {
public:
Complex (double re = 0, double im = 0): m_re (re), m_im (im) {}
protected:
double m_re;
double m_im;
};
或者,除非此类代码是出于学习目的,否则您只能使用std::complex
。