printDad功能帮助 [英] printDad function help

查看:73
本文介绍了printDad功能帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

............................................... ..................................

.................................................................................

推荐答案

printDad函数中,替换
In printDad function, replace
成员8186414写道:
Member 8186414 wrote:

cout<< p.getAge(p.getDad())<< endl;

cout << p.getAge(p.getDad()) << endl;




with

cout << p.getDad()->getAge() << endl;


与问题不完全相关,但...
注意
Not strictly related to the question but ...
Be careful about
void printDad(Person p) 


实际上,它不是指您所指的人,而是指它的副本.
由于C ++默认副本构造函数是如何工作的,因此具有相同的成员值(因此指向相同的父母),因此顺便说一遍也可以,但实际上是临时兄弟".
传递指针或引用,而不是值.

另外,学习使用const 表示不修改对象的成员函数,使用const&表示参数.您将避免大量无用的副本.


It actually doesn''t refer to the person you mean, but to a copy of it.
That -because of how C++ default copy constructor works- has the same members values (hence point to the same mom and dad) and hence incidentally will work the same, but it is actually a "temporary brother".
Pass a pointer or a reference, not a value.

Also, learn to use const for member function that don''t modify the object, and const& for parameters. You''ll avoid a lot useless copy.


void printDad(Person& p) // cause i cant see a copy constructor
{
  if(p.getDad())
    cout << p.getDad()->getAge() << endl;
  else
    cout << "orphan" << endl;
}


或实现副本构造函数:


or implement a copy constructor:

class Person
{
  Person* mom,
  *       dad;
  int     age;
public:
  Person(){ mom=dad=0; age=0; }
  Person(Person& init){ mom=init.mom; dad=init.dad; age=init.age; }
   // the others
};


祝你好运.


Good luck.


这篇关于printDad功能帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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