问题描述
- C++ 关于一个成员函数的实现问题
-
/*CArray是我写的、能够运行的、利用类来实现动态创建数组的工程,现在要加一个成员函数,要求如上,我把我理解的操作都写了下来,但我的疑问是在第一个判断条件中,函数返回要怎么写,是要跳过这个函数吗?除了这点,我下面写的实现过程有错吗?在main函数中能够输出对象obj1 resize后的数组吗?请大神们多多指教~*/
#include <iostream> using namespace std; class CArray{ public:CArray(unsigned int length=0); public: void print(); void set(); void resize(unsigned int length=0); private: double *m_data; unsigned int m_nLength; }; void CArray::resize(unsigned int length) { if(length==m_nLength) //函数返回要怎么写?? else delete []m_data; if(length==0) m_data=NULL; else m_data=new double[length]; m_nLength=length; cout<<"请输入"<<m_nLength<<"个数:"; unsigned int i; for(i=0;i<m_nLength;i++) cin>>m_data[i]; } CArray::CArray(unsigned int length) { m_nLength=length; if( length==0) m_data=NULL; else m_data=new double[length]; } void CArray::set() { if( m_nLength==0) m_data=NULL; cout<<"请输入"<<m_nLength<<"个数:"; for(unsigned int i=0;i<m_nLength;i++) cin>>m_data[i]; } void CArray::print() { if( m_nLength==0) m_data=NULL; unsigned int index; for(index=0;index<m_nLength;index++) cout<<m_data[index]<<" "; } int main(int argc, char* argv[]) { unsigned int size; cout<<"请输入数组长度:"; cin>>size; CArray obj(size); obj.set(); cout<<"输入的数组为:"; obj.print(); CArray obj1; obj1.resize(3); obj1.print(); return 0; }
时间: 2025-01-24 08:56:56