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