gpt4 book ai didi

c++ - 改变指针指向什么?

转载 作者:行者123 更新时间:2023-11-30 02:33:30 31 4
gpt4 key购买 nike

我是编程的新手,这个程序快要结束了,但还不能完全完成我一直坚持的最后一个细节。我正在尝试切换 *sp 指向的形状指针,在我看来我正在做的事情应该有效,因为矩形和圆形都是形状;但是,当我编译时,只有颜色值发生变化。圆的面积打印而不是矩形的面积,周长打印 0。任何帮助将不胜感激!

#include <iostream>
#include <string>
using namespace std;
double const pi = 3.1519;
class shape {
public:
shape() {};
shape(string);
virtual double getCircumference() {
return 0;
};
virtual double getPerimeter() {
return 0;
};
virtual double getArea() {
return 0;
};
string getColor();


protected:
string color;

};

string shape::getColor() {
return color;
}

class circle : public shape {
public:

circle(double r, string c) {

radius = r;
color = c;
};
double getArea();
double getCircumference();


private:
double radius;


};
double circle::getCircumference() {
return pi * radius * 2;
}
double circle::getArea() {
return pi * radius * radius;
}
class rectangle:public shape {

public:

rectangle(double w, double l, string c) {
width = w;
length = l;
color = c;
};

double getArea();
double getPerimeter();

private:
double length;
double width;

};
double rectangle::getPerimeter() {
return width * 2 + length * 2;
}
double rectangle::getArea() {
return length * width;
}
void change(shape *sp, shape *sp1) {
*sp = *sp1;
}
int main() {

circle mary(3.2, "Green");
shape *sp = new circle(4.5, "Yellow");

cout << "Circle #1 is " << mary.getColor() << endl;
cout << "Circle #1 has an area of " << mary.getArea() << endl;
cout << "Circle #1 has a circumference of " << mary.getCircumference() << endl << endl;
cout << "Circle #2 is " << sp->getColor() << endl;
cout << "Circle #2 has an area of " << sp->getArea() << endl;
cout << "Circle #2 has a circumference of " << sp->getCircumference() << endl << endl;

shape *sp1 = new rectangle(1.0, 2.1, "Red");

change(sp, sp1);

cout << "Rectangle #1 is " << sp->getColor() << endl;
cout << "Rectangle #1 has an area of " << sp->getArea() << endl;
cout << "Rectangle #1 has a perimeter of " << sp->getPerimeter() <<endl<< endl;

}

最佳答案

重要的是要牢记各种不同的指针使用方式的含义。在你的程序中,sp指的是指针本身——也就是告诉计算机在哪里可以找到对象的内存位置。 *sp 中的星号是一个“解引用”运算符;它需要一个指针并为您提供它所指向的东西。

考虑到这一点,您的线路 *sp = *sp1;是说,‘拿那个 sp 的东西指向,并将其设置为等于 sp1 的东西指向。’换句话说,您正在更改 sp 指向的对象的值。 , 不是 sp 的值本身。来点spsp1 指向的对象处, 你需要 sp = sp1;没有星号。

另一件要记住的事情是,C++ 默认情况下按值传递函数参数:当函数被调用时,参数被复制,函数对拷贝进行操作。这意味着原始参数本身不能被像这样工作的函数改变。在参数声明中添加一个符号,例如 void change(shape *&sp, shape *sp1)导致第一个参数通过引用传递:函数操作的对象与调用代码传入的对象相同。这允许函数更改作为参数传递的对象,并在函数返回后保留这些更改。

很抱歉回答很长:我本可以给你几行来完成你想要的,但我想你可能会喜欢解释为什么事情会这样运作的原因。

关于c++ - 改变指针指向什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35369968/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com