【问题标题】:'x' was not declared in this scope'x' 未在此范围内声明
【发布时间】:2017-03-06 11:41:05
【问题描述】:

我想重载代码块中的插入和提取运算符。
这是我的代码:

#include<iostream>  
#include<conio.h>  

    enter code here

 using namespace std;

 class point
 {
    private:
    int x,y;
    public:
    point(int a, int b){
    a=x;
    b=y;
    }
 friend istream &operator >>(istream &i, point &p);
 friend ostream &operator <<(ostream &o, point &p);
 };

 istream &operator>>(istream &i, point &p)
 {
     cout << "Enter the coordinates of x and y";
     i >> x >> y;
     return i;
 }
 ostream &operator<<(ostream &o, point &p)
 {
     cout << "coordinates are :";
     o << x << endl;
     o << y;
     return o;
 }

 void main()
 {
     point p1(3,4);
    cin  >> p1;
    cout << p1;
 }

我收到以下错误:

“x”未在此范围内清除

“y”未在此范围内清除

请帮助解决这个问题。

【问题讨论】:

  • 函数中的point() x 变量未知。
  • i &gt;&gt; x &gt;&gt; y; -> i &gt;&gt; p.x &gt;&gt; p.y;
  • 也在你的构造函数中:` a=x; b=y;` 你的意思可能正好相反:x=a; y=b;,但最好还是使用point(int a, int b) : x(a), y(b) { }
  • 如果你的问题得到解决,关闭一个问题总是一个好主意:)

标签: c++ class operator-overloading


【解决方案1】:

显然它们对你的操作符函数是不可见的,因为它们是在类中声明的。

您需要通过对象 p 访问它们。例如。 p.xp.y

【讨论】:

    【解决方案2】:
    point(int a, int b){
        x = a;
        y = b;
    }
    

    【讨论】:

    • 并使用 p.x 和 p.y 访问
    • 这个答案(非常巧妙地)指出了代码的问题,但实际上并没有解释所询问的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2016-08-09
    • 2019-02-17
    • 2021-01-07
    • 2016-10-27
    相关资源
    最近更新 更多