【问题标题】:C++: Instance of class in another classC ++:另一个类中的类实例
【发布时间】:2017-12-22 18:24:46
【问题描述】:

我有一个名为Matrix 的类和一个名为NeuralNet 的类。 它们看起来像这样:

Matrix.h

class Matrix
{
  public:
  double * matrix = nullptr;
  Matrix(int,int);
};

Matrix.cpp

#include "Matrix.h"
Matrix::Matrix(int h,int w)
{
  matrix = new double[h*w];
};

我的问题是:“如何在 NeuralNet 类中使用此类的实例?” 我试过了:

NeuralNet.h

class NeuralNet
{
  public:
  Matrix * ptr = nullptr;
  NeuralNet(int,int);
}

NeuralNet.cpp

#include "Matrix.h"
#include "NeuralNet.h"
NeuralNet::NeuralNet(int h,int w)
{
  ptr = new Matrix(h,w);
}

这不起作用,我收到错误:

  Missing ';' before n'*'

我们将不胜感激任何类型的帮助! 谢谢

【问题讨论】:

  • 如果在} 之后为class NeuralNet 添加; 会怎样?
  • Matrix 应该是matrix
  • 你刚刚添加的分号完全没有任何作用
  • 只是一个错字。为什么矩阵应该是矩阵?
  • @AlessandroLegnani 因为 C++ 区分大小写。

标签: c++ class oop pointers visual-c++


【解决方案1】:

在NeuralNet.h中,需要预先声明Matrix:

class Matrix;

或者包括它:

#include "Matrix.h"

另外,在 Matrix.cpp 中,

Matrix::Matrix(int h,int w)
{
   Matrix = new double[h*w];
}

应该是

Matrix::Matrix(int h,int w) :
   matrix( new double[h*w] )
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    相关资源
    最近更新 更多