【问题标题】:Cannot use method returned value into another method不能将方法返回值用于另一个方法
【发布时间】:2019-03-29 09:28:48
【问题描述】:

所以我一直在尝试在另一个方法中使用我的类中某些方法的返回值,但我遇到了这个问题“无法解析标识符”

class Puncte{
public:
    double mx;
    double my;

    Puncte(double x, double y) {
        mx = x;
       my = y;
    }
    double distanta (){
        double r = sqrt(mx*mx + my*my);
        return r;
    }
    double phi (){
        double unghi = atan(my/mx) * 180.0 / PI;
        if(unghi > 0 && mx < 0 && my < 0) unghi = unghi + 180;
        if (unghi < 0 && mx>0 && my < 0) unghi = unghi + 360;
        if (unghi < 0 && mx<0 && my > 0) unghi = unghi + 180;
        return unghi;
    }
    virtual  mprint(){

        printf("r=%.3f; phi=%.3f\n",r,unghi) ; //unable to resolve identifier
    }
};

有人可以帮忙吗? 谢谢:)

【问题讨论】:

  • printf("r=%.3f; phi=%.3f\n",distanta(),phi()); 你需要调用函数,而不是尝试访问那里的返回值。
  • 另见"the Scope of (Local) Variables' - 第一个示例还展示了如何使用调用函数的返回值。

标签: c++ oop


【解决方案1】:

使用@super 的建议和一些警告修复。

@super 建议的两个重要更改在该行中:

printf("r=%.3f; phi=%.3f\n",distanta(),phi());

变量“r”和“unghi”都是成员函数的局部变量,不能在这些函数之外访问。 “distanta()”和“phi()”成员函数准确地提供了 printf 中所需的内容,并且是获取所需值的完美方式。

另一个变化是明确声明 mprint() 是一个 void:

void mprint(){

C++ 中的所有函数(甚至是 main!)都必须有返回类型。还删除了“虚拟”,因为没有派生类(我不得不将该函数移动到该类的公共部分以使其保持为虚拟)。

我已经添加了 include 和 main() 函数,因此任何阅读此代码的人都可以将其剪切并粘贴到他们的编译器中,从而获得一个工作版本,而无需更多的努力。

进一步清理将 mx 和 my 变成私有变量,以防止该类的用户能够修改这些变量。

#include <cmath>
#include <cstdio>
#include <iostream>


class Puncte{
private:
    double mx;
    double my;
public:
    Puncte(double x, double y) {
        mx = x;
        my = y;
    }
    double mx() {return mx;}
    double my() {return my;}

    double distanta (){
        double r = sqrt(mx*mx + my*my);
        return r;
    }
    double phi (){
        double unghi = atan(my/mx) * 180.0 / M_PI;
        if(unghi > 0 && mx < 0 && my < 0) unghi = unghi + 180;
        if (unghi < 0 && mx>0 && my < 0) unghi = unghi + 360;
        if (unghi < 0 && mx<0 && my > 0) unghi = unghi + 180;
        return unghi;
    }
void mprint(){

        printf("r=%.3f; phi=%.3f\n",distanta(),phi()) ; //unable to resolve identifier
    }
};

int main() {
    Puncte puncte(3.5, 8.9);

    std::cout << "Point(" << puncte.mx() << ", " << puncte.my() 
        << "): radius = " << puncte.distanta() << std::endl;

    return 0;
}

输出:

$> main
Point(3.5, 8.9): radius = 9.56347

Process finished with exit code 0

【讨论】:

  • @user4581301,有用的建议。
  • 没有过度相关,仅供参考,但您应该更喜欢to include <cxxxx> rather than <xxxx.h>
  • 我为访问函数创建了一个公共部分并删除了 virtual 关键字,因为如果没有派生类或需要派生类的建议,它似乎是多余的。
  • 有用的建议,@user45813011。我不知道 cxxxx 包含文件。我会记住那个!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 2021-07-07
  • 2017-03-19
  • 2023-04-03
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
相关资源
最近更新 更多