2016-09-23 73 views
0

我正在学习C++中的继承,并尝试从函数“age”中返回值。我回来的只有0个。我花了好几个小时才弄清楚,但没有运气。这是我的代码如下。我将不胜感激任何帮助!无法返回函数的值

.H类

#include <stdio.h> 
#include <string> 
using namespace std; 

class Mother 
{ 
public: 
    Mother(); 
    Mother(double h); 

    void setH(double h); 
    double getH(); 

    //--message handler 
    void print(); 
    void sayName(); 
    double age(double a); 

private: 
    double ag; 
}; 

的.cpp

#include <iostream> 
#include <string> 
#include "Mother.hpp" 
#include "Daughter.hpp" 
using namespace std; 

Mother::Mother(){} 

Mother::Mother(double h) 
{ 
    ag=h; 

} 

void setH(double h){} 
double getH(); 

void Mother::print(){ 
    cout<<"I am " <<ag <<endl; 
} 


void Mother::sayName(){ 
    cout<<"I am Sandy" <<endl; 
} 

double Mother::age(double a) 
{ 
    return a; 
} 

主要

#include <iostream> 
#include "Mother.hpp" 
#include "Daughter.hpp" 
using namespace std; 

int main(int argc, const char * argv[]) { 
    Mother mom; 
    mom.sayName(); 
    mom.age(40); 
    mom.print(); 

    //Daughter d; 
    //d.sayName(); 
    return 0; 
+1

是母亲::年龄应该设置'this-> ag'?现在你只需返回它。 – Falmarri

+0

对不起,我不明白你的意见,请你详细说明一下吗?谢谢! – familyGuy

+1

这听起来像是如果你不了解我的评论,你需要回头继续学习C++。在了解继承之前,您应该了解对象,变量,值和方法。 – Falmarri

回答

2

功能年龄不分配值的成员公司,而是它返回的值它作为参数是一件很糟糕的事情。 得到我想要在主写说什么:

cout << mom.age(40) << endl; // 40 

,使其正确的改变,你的作用年龄:

double Mother::age(double a) 
{ 
    ag = a; 
    return a; // it's redundant to do so. change this function to return void as long as we don't need the return value 
} 

***另一件事你应该做的:

化妆“getters”常量,以防止更改成员数据,只让“setter”不是常量。例如,在你的代码:class母亲:

double getH()const; // instead of double getH() const prevents changing member data "ag" 
+0

谢谢@ Raindrop7。那样做了! – familyGuy

+0

@familyGuy欢迎!如果它能够工作,将它作为被接受的答案 – Raindrop7

3

你mom.print()做到这一点:

cout<<"I am " <<ag <<endl; 

所以这里的问题是:AG = 0

你mom.age(40 )做到这一点:

return a; 

看,这不你妈妈的年龄保存到您的mom变量,它只能返回你传递什么(她e是40),那么它如何打印?

因此,有很多方法可以解决这个问题,如果你想回到你妈的年龄,做COUT在main() 或者,只是< < mom.age(40):

void Mother::age(double a) 
{ 
    ag = a; 
} 
2

你必须正确使用setter和getter。使用setter来更改像这样的年龄:

void setAge(const double &_age) { 
    ag = _age; 
} 

如果要检索值,请使用getter。

double getAge() const { 
    return ag; 
}