C ++类,面向对象编程 [英] C++ classes , Object oriented programming

查看:317
本文介绍了C ++类,面向对象编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的类名为person,如下所示,我有一个问题,只有两个函数,即setstring()函数和setname()函数,我从setname函数调用setstring()函数。
唯一的问题是在main函数中写入

Object.setname(Zia);

结果是确定,如输出屏幕所示:
现在当我写入

Object.setname(Zia ur Ra​​hman);

不显示任何内容,您可以看到输出屏幕。



我知道问题是当我将名称指针传递给setstring我很困惑,请详细解释这里发生了什么。

 #include< iostream.h> 
class person
{
char * name;
public:
person();
void setname(const char *);
void setstring(const char *,char *);
void print()const;
};
person :: person()
{
name = new char [3];
strcpy(name,NILL);
name [3] ='\0';
}
void person :: setstring(const char * s,char * p)
{
if(s!= NULL)
{
delete [] p;
p = new char [strlen(s)];
strcpy(p,s);
p [strlen(s)] ='\0';
}
}
void person :: setname(const char * n)
{
setstring(n,name); //传递数据成员名
}
void person :: print()const
{
cout<<Name:<<
}
main()
{
person object;
object.setname(Zia ur Ra​​hman);
object.print();
system(pause);
}



解决方案

无法打印的具体原因是 setstring p 是名称指针的副本,而不是对它的引用。尝试将 setstring 的签名更改为:

  void setstring * s,char *& p); 

(请注意& )。 / p>

查看代码中其他重大错误的其他答案 - 除非这些问题已修复,否则可能会导致崩溃或异常行为。



除非代码的目的只是学习动态数组,否则使用 std :: string : - )。


I have a very simple class named person which is given below , I have a problem with only two functions , i.e setstring () function and setname() function , I am calling setstring() function from the setname function. The only problem is when in the main function I write
Object.setname("Zia");
The result is ok as shown in the output screen, Now when I write
Object.setname("Zia ur Rahman");
Nothing is displayed as you can see the output screen.

I know the problem is when I pass the name pointer to setstring () function but I am confused about it please explain it in detail that what is happening here.

#include<iostream.h>
class person
{
char* name;
public:
person();
void setname(const char*);
void setstring(const char*, char*);
void print()const;
};
person::person()
{
name=new char[3];
strcpy(name,"NILL");
name[3]='\0';
}
void person::setstring(const char* s, char*p)
{
if(s!=NULL)
{
delete[] p;
p=new char[strlen(s)];
strcpy(p,s);
p[strlen(s)]='\0';
}
}
void person::setname(const char* n)
{
setstring(n, name);//passing data member name
}
void person::print()const
{
cout<<"Name: "<<name<<endl;
}
main()
{
person object;
object.setname("Zia ur Rahman");
object.print();
system("pause");
}

解决方案

The specific reason that nothing is being printed is that in setstring, p is copy of the name pointer, not a reference to it. Try changing the signature of setstring to:

void setstring(const char* s, char*& p);

(note the &).

See the other answers for other significant errors in the code - unless these problems are fixed, you are likely to get crashes or strange behaviour.

And unless the purpose of the code is just to learn dynamic arrays, use std::string instead :-).

这篇关于C ++类,面向对象编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆