C++类构造函数()

标签 c++ oop constructor

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

难道我的构造函数不应该也替换 void arguments 构造函数吗?它抛出一个错误 util 我也声明了 Complex() 构造函数。 g++-std=c++14

复杂.h

class Complex {

private:
    int m_real, m_imaginary;

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

复杂.cpp

#include "Complex.h"

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

矩阵.h

class Complex;

class Matrix {

private:
    int m_lines, m_columns;
    Complex *m_matrix;

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

矩阵.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()”|

最佳答案

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

关于C++类构造函数(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42785223/

相关文章:

c++ - 我什么时候使用引用?

c++ - cpp 文件中的内联构造函数和析构函数

python - 属性错误: 'Employee' object has no attribute 'WorkingHours'

c++ - 尝试在类的构造函数中复制变量时出错

java - 深拷贝似乎不起作用

c++ - 我应该如何在菱形模式中调用父 move 构造函数?

c++ - 删除字符串流中的最后一个字符?

c# - C# 中 C++ 1i64 移位的等效项是什么

Java重载和覆盖

C++类,面向对象编程