繁体   English   中英

C ++类Constructor()

[英]C++ class Constructor()

我有两个类:Complex类和Matrix类。

我的构造函数是否也应该替代void参数构造函数? 也会抛出一个错误,直到我声明了Complex()构造函数。 g ++ -std = c ++ 14

复杂度

class Complex {

private:
    int m_real, m_imaginary;

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

复杂文件

#include "Complex.h"

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

矩阵

class Complex;

class Matrix {

private:
    int m_lines, m_columns;
    Complex *m_matrix;

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

矩阵文件

#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()'|

同样在这里-我根据您的描述测试了我编写的代码。 它可以在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;
}

看来您的错误在其他地方。 正如某些程序员的观点所指出的那样,您可以通过一个最小,完整和可验证的示例来解决这个问题-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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM