无法从函数返回值
Not able to return the value from a function
我正在学习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;
你的妈妈。print()这样做:
cout<<"I am " <<ag <<endl;
这里的问题是:ag = 0
你的妈妈年龄(40)这样做:
return a;
看,它不会把你妈妈的年龄保存到你的mom
变量中,它只返回你传递的值(这里是40),所以它怎么能打印出来呢?
因此,有很多方法可以解决这个问题,如果你想返回你妈妈的年龄,做count <<年龄(40岁)主要()或者,只是:
void Mother::age(double a)
{
ag = a;
}
函数age没有将值a赋值给成员ag,而是返回值a作为参数,这是一件很糟糕的事情。为了得到我想在main中说的话,写:
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
}
***你应该做的另一件事:
使"getter "为const以防止改变成员数据,只让"setter "为非常量。例如在你的代码中:class mother:
double getH()const; // instead of double getH() const prevents changing member data "ag"
必须正确使用setter和getter。使用setter来更改年龄,如下所示:
void setAge(const double &_age) {
ag = _age;
}
如果要检索值,请使用getter。
double getAge() const {
return ag;
}
相关文章:
- 从python中调用C++函数并获取返回值
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 程序不向函数返回值
- 如何在另一个函数中使用返回值作为参数?
- 编写以 C++ 为单位返回值的函数
- 了解在返回值之前和之后使用 EAX 的函数调用
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 如何将不可移动和不可复制的函数返回值获取到数组中
- G++ 编译器是否在未使用返回值的情况下将 constexpr 函数视为常规函数?
- 为什么当你将函数的返回值乘以零时它不会短路?
- 函数的返回值类型是别名 ***或 *** 布尔值
- 如何在没有返回值的情况下使用(特征)unaryExpr 和 lambda 函数?
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 为什么这个"ctypes"包装函数的返回值是"c_long(0)"而不是&quo
- 函数不显示返回值 - C++
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 将 void 函数更改为返回值函数
- 返回值函数中结构成员赋值的额外拷贝