簡體   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