目标c-在c++中用指针在类中输入数据

objective c - inputting data with pointers in class in c++

本文关键字:输入 数据 指针 c++ 目标      更新时间:2023-10-16

我想写一段代码(使用指针)来获取矩形的两侧并计算其周长和面积,但它不起作用代码来了:

#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
class PAndArea{
private:
    int x, y;
    void getxy(int *,int *);
    int area(int *, int *);
    int perimeter(int *, int *);
public:
    void showperimeterandarea(int *, int *);
};
void PAndArea::showperimeterandarea(int *w, int *e)
{
    getxy(*w, *e);
    cout << "area:"<<area(*w, *e)<< "<br>";
    cout << "perimeter:" << perimeter(*w, *e);
}
void PAndArea::getxy(int *x, int*y)
{
    cout << "enter two numbers:";
    cin >> *x >> *y;
}
int PAndArea::area(int *x,int *y)
{
    return (*x * *y);
}
int PAndArea::perimeter(int *x, int *y)
{
    return((*x * 2) + (*y * 2));
}
int main(){
    int x, y;
    PAndArea i;
    i.showperimeterandarea(&x, &y);
    _getch();
    return 0;
}

您正在将int传递给一个接受int指针的函数。

int area(int *, int *);
//...
area(*w, *e);

w和e是int*。当您在调用中取消引用它们时,a*w和*e是int(而不是指针)。

可以将area函数更改为int,也可以将指针传递到area。

    int area(int *, int *);
    //...
    area(w, e);
    // or
    int area(int, int);
    //...
    area(*w, *e);

您在其他调用中也会犯同样的错误。例如:

void PAndArea::showperimeterandarea(int *w, int *e)
{
   // getxy(*w, *e);  // you are passing int's here, not pointers.  This is wrong
   getxy(w, e);  // correction