gpt4 book ai didi

c++ - 初始化基类的引用成员

转载 作者:行者123 更新时间:2023-11-30 05:38:06 24 4
gpt4 key购买 nike

经过长时间的禁欲,我目前正在尝试刷新我的 C++ 技能。因此,我正在实现一个微型绘图圆圈图像程序。

场景:我有一个名为 Shape 的基类,它基本上由一个成员组成,该成员是对表示中心的 Point 的引用。 是一种形状,除了圆心外,它还有一个半径。

class Shape
{

public:
Shape(Point& p);
~Shape();
Point& get_center() const;

private:
Point& center;
};

-

class Point
{
public:
Point();
Point(float x, float y);
Point(short d);
~Point();
float get_x() const;
float get_y() const;
friend std::ostream& operator<< (std::ostream& stream, const Point& p);

private:
short dimension;
float x, y;
};

//.cpp
std::ostream& operator<<(std::ostream &strm, const Point &p) {
return strm << "Point(" << p.get_x() << "," << p.get_y() << ")";
}

-

class Circle :
public Shape
{
public:
Circle(Point p);
Circle(Point p, float radius);
~Circle();
float get_radius() const;

private:
float radius;
typedef Shape super;
};

成员的初始化执行如下:

Circle::Circle(Point p, float rad) : Shape(p), radius(rad)
{
std::cout << "Called circle constructor with center point " << p << std::endl;
}

Shape::Shape(Point& p) : center(p) {
std::cout << "Called Shape constructor with point " << p << "a" <<std::endl;
}

如果我随后运行以下代码,中心变量似乎未正确设置,导致下面给出的输出 A。奇怪的是,如果我将更多输出附加到 Shape 构造函数(在此示例中为字母“a”),则似乎设置了对中心 Point 的引用(输出 B ).此外,两个 Circle 似乎引用了相同的 Point?!有人可以解释为什么会这样吗?处理这种情况的合适方法是什么?

Circle& cir1 = *(new Circle(Point(400, 550), 50));
Circle& cir2 = *(new Circle(Point(300, 550), 80));

vector<Circle> circles { cir1, cir2 };

cout << "Iterating circles" << endl;
for (auto& cir : circles)
{
cout << "Radius: "<< cir.get_radius() << " center: " << cir.get_center() << endl;
}

输出A:

Called Shape constructor with point Point(400,550)
Called circle constructor with center point Point(400,550)
Called Shape constructor with point Point(300,550)
Called circle constructor with center point Point(300,550)
Iterating circles
Radius: 50 center: Point(1.87436e-38,1.87419e-38)
Radius: 80 center: Point(1.87436e-38,1.87419e-38)

输出 B:

Called Shape constructor with point Point(400,550)a
Called circle constructor with center point Point(400,550)
Called Shape constructor with point Point(300,550)a
Called circle constructor with center point Point(300,550)
Iterating circles
Radius: 50 center: Point(300,550)
Radius: 80 center: Point(300,550)

最佳答案

这里有个问题:

Circle::Circle(Point p, float rad) : Shape(p), radius(rad)

{
std::cout << "Called circle constructor with center point " << p << std::endl;
}

Shape::Shape(Point& p) : center(p) {
std::cout << "Called Shape constructor with point " << p << "a" <<std::endl;
}

因为 Shape 存储了对 Circlep 参数的引用。在构造结束时,参数消失。

我可能不会存储一个引用,而是一个值。这样你就有了参数的拷贝。复制一个 Point 并不是很昂贵。

关于c++ - 初始化基类的引用成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32935003/

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