【问题标题】:Overload - not in scope过载 - 不在范围内
【发布时间】:2013-02-22 21:37:43
【问题描述】:

我收到以下错误:

circleType.cpp||In function 'std::ostream& operator<<(std::ostream&, circleType&)':|
circleType.cpp|48|error: 'getRadius' was not declared in this scope|
circleType.cpp|49|error: 'circumference' was not declared in this scope|
circleType.cpp|50|error: 'area' was not declared in this scope|
||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|

在这里发现错误:

ostream& operator <<(ostream& outs, circleType& circle1)
{
   outs << "radius: " << getRadius() << endl
   << "circumference: " << circumference() << endl
   << "area: " << area() << endl;
   return outs;
}

以圆周函数为例:

double circleType::circumference()
{
    return (radius*2*pi);
}

头文件:

class circleType
{
public:
    circleType(); // færibreytulaus smiður
    circleType(double the_radius);
    double getRadius();
    void setRadius(double the_radius);
    double area();
    double circumference();
    friend ostream& operator <<(ostream& outs, circleType& );
private:
    double radius;
};

主要:

circleType circle1(3.0);
cout << "circle1:" << endl;
cout << "--------" << endl;
cout << circle1 << endl;

所有标题都包含在任何地方。我仍然对重载功能有点困惑,任何帮助。

【问题讨论】:

    标签: c++ class compiler-errors overloading


    【解决方案1】:

    您没有在输入对象上调用成员函数 (circle1);相反,您正在尝试调用一些不存在的具有相同名称的 global 函数(请注意,friend 函数不是它是朋友的类的成员函数,但是而是一个免费的非成员函数,已被授予访问类内部的权限)。

    要解决此问题,请更改重载operator &lt;&lt; 的定义,如下所示:

    ostream& operator << (ostream& outs, circleType& circle1)
    {
       outs << "radius: " << circle1.getRadius() << endl
       << "circumference: " << circl1.circumference() << endl
       << "area: " << circle1.area() << endl;
       return outs;
    }
    

    【讨论】:

    • 啊,是的。我还在学习课程的窍门,非常感谢。像魅力一样工作。
    • 我仍然面临一个问题:如果我想制作 circle2, 3, 4, ..., 怎么办?那我显然做不到:circle1.area()
    • @Zanii:我不明白你的意思。你可能对你想要达到的目标有一些误解。玩一会儿这些东西,你应该会掌握它的窍门。
    • 假设我想创建一个名为 circle2 的新 circleType 对象。现在我不能使用 "outs
    • @Zanii:正如我所想,你有一个误解。 circle1 只是函数参数的名称。如果您使用名为circle2 或bingo 的对象调用它,则该对象仍将在函数内以circle1 的名称引用。这是基础。我建议你阅读一些关于 C++ 的教程或入门书籍
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多