2017-03-14 141 views
0

我有两个类:复合类和类矩阵。C++类构造函数()

不是我的构造函数应该替代void参数构造函数吗?它会抛出一个错误util我也声明Complex()构造函数。克++ -std = C++ 14

Complex.h

class Complex { 

private: 
    int m_real, m_imaginary; 

public: 
    Complex(const int, const int); 
} 

complex.cpp

#include "Complex.h" 

// Constructor 
Complex::Complex(const int real = 0, const int img = 0) : m_real(real), m_imaginary(img) { } 

Matrix.h

class Complex; 

class Matrix { 

private: 
    int m_lines, m_columns; 
    Complex *m_matrix; 

public: 
    Matrix(const int, const int, const Complex &); 
} 

matrix.cpp

#include "Matrix.h" 
#include "Complex.h" 

Matrix::Matrix(const int nr_lines, const int nr_columns, const Complex &comp) : m_lines(nr_lines), m_columns(nr_columns) { 
    m_matrix = new Complex[nr_lines * nr_columns]; 
    some other code goes here... 

| 7 |错误:没有用于调用'Complex :: Complex()'的匹配函数|

+4

您可以尝试创建一个[最小化,完整和可验证示例](http://stackoverflow.com/help/mcve)并向我们展示?加上你得到的实际错误(完整,完整和未经编辑)? –

+0

而不是原始数组,为什么不使用'std :: vector'? – crashmstr

+0

请提供更多的上下文。如果有错误,则将错误消息的文本复制到您的问题。如果这是Visual Studio,则“输出”选项卡将出现可作为文本复制的窗体中的错误。 – drescherjm

回答

1

看来你的错误是在别的地方。 作为一些程序员花花公子指出的那样,你可以有一个最小的,完整的和可核查的例子想通了这一点 - https://stackoverflow.com/help/mcve

我创建了一个小例子:

#include <iostream> 
#include <stdlib.h> 

class Complex { 
    private: 
     int m_n; 
     int m_i; 

    public: 
     Complex (const int n = 0, const int i = 0) : m_n (n), m_i (i) { 
      std::cout << "Complex ctor: " << n << ", " << i << std::endl; 
     }; 
}; 

int main(int argc, char** argv) { 
    int cnt = 12; 
    if (argc > 1) 
     cnt = atoi (argv[1]); 
    Complex* m = new Complex[cnt]; 
    (void)m; //no warning for unused variable 
    return 0; 
} 

楼内有g ++以及运行:

pan:~$ g++ example.cpp -Wall -o example.elf 
pan:~$ ./example.elf 4 
Complex ctor: 0, 0 
Complex ctor: 0, 0 
Complex ctor: 0, 0 
Complex ctor: 0, 0 
pan:~$ 

正如你所看到的,这C++类的构造方法效果很好&预期

我的gcc是g ++(SUSE Linux)4.8.5

2

同样在这里 - 我测试了我根据您的描述编写的代码。 它在VS2015,VS2017上编译和运行得很好。

class Complex 
{ 
private: 
    int m_real; 
    int m_img; 

public: 
    Complex(const int real = 0, const int img = 0) 
     : m_real(real) 
     , m_img(img) 
    { 

    } 
}; 

class Matrix 
{ 
private: 
    Complex* matrix; 

public: 
    Matrix(int nr_lines = 3, int nr_columns = 3) 
    { 
     matrix = new Complex[nr_lines * nr_columns]; 
    } 

    ~Matrix() 
    { 
     delete[] matrix; 
    } 
}; 

int main() 
{ 
    Matrix* t = new Matrix(); 
    return 1; 
} 
+0

你的问题在复杂构造函数的声明中,在complex.h文件中。在那里,你没有声明默认值。从complex.cpp复制构造函数的签名,它应该工作 –