Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 不兼容的类声明c++;_C++_Class_Declaration - Fatal编程技术网

C++ 不兼容的类声明c++;

C++ 不兼容的类声明c++;,c++,class,declaration,C++,Class,Declaration,我在NumberArray.h class NumberArray { private: double *aPtr; int arraySize; public: NumberArray(int size, double value); // ~NumberArray() { if (arraySize > 0) delete [ ] aPtr;} //commented out to avoid problems with the //default copy

我在
NumberArray.h

class NumberArray
{
private:
  double *aPtr;
  int arraySize;

public:
  NumberArray(int size, double value);

  // ~NumberArray() { if (arraySize > 0) delete [ ] aPtr;}
  //commented out to avoid problems with the
  //default copy constructor
  void print() const; 
  void setValue(double value);
};
当我在NumberArray.cpp中编写打印函数时

void NumberArray::print()
{
  for (int index = 0; index < arraySize; index++)
    cout << aPtr[index] << "  ";
}
void numberraray::print()
{
for(int index=0;indexcout您忘了在函数定义的签名中添加
const
限定符(以及分号)

你必须做到:

void NumberArray::print() const
{
  for (int index = 0; index < arraySize; index++)
    cout << aPtr[index] << "  ";
}
void numberraray::print()常量
{
for(int index=0;index无法在语句末尾看到分号“;”,无法
void print()const;
vs
void NumberArray::print())
--您现在能发现差异吗?您声明了一个
常量
函数,但将其实现为非
常量
。它们不是一回事。为什么要在打印函数中指定常量参数?该代码确实包含一个;在语句末尾,出于某种奇怪的原因,只是忘记了包含它。decl是一种很好的做法作为
const
任何不打算更改对象的方法。如果您违反约定,编译器会警告您。在不应有副作用的方法中更改对象(如
numaray::print()
)可能会触发很难找到的bug。不知道该定义需要类外的常量。感谢您对此进行澄清。@Jeffrey Dilley,否则函数签名将如何匹配?常量和非常量成员函数之间有很大的区别,类可以包含具有相同属性的两个名称(重载)。