gpt4 book ai didi

c++ - 指向用户定义结构的智能指针的成员初始化列表

转载 作者:行者123 更新时间:2023-11-30 05:19:53 25 4
gpt4 key购买 nike

下面是程序。它只是一个基于 2 点的矩形。我的问题是 Rectangle 构造函数。

#include <iostream>
#include <memory>


class Point { // class for representing points
public:
Point(int x, int y);

void setX(int newVal);
void setY(int newVal);
};

struct RectData { // Point data for a Rectangle
Point _ulhc; // ulhc = “ upper left-hand corner”
Point _lrhc; // lrhc = “ lower right-hand corner”
};

class Rectangle {
public:
Rectangle(Point ulhc, Point lrhc) :
_pData->_ulhc(ulhc), _pData->_lrhc(lrhc)
{}

Point & upperLeft() const { return _pData->_ulhc; }
Point & lowerRight() const { return _pData->_lrhc; }

private:
std::tr1::shared_ptr<RectData> _pData;
};

int main()
{
Point coord1(0, 0);
Point coord2(100, 100);
const Rectangle rec(coord1, coord2); // rec is a const rectangle from
// (0, 0) to (100, 100)
rec.upperLeft().setX(50); // now rec goes from
// (50, 0) to (100, 100)!

return 0;
}

看来我没有正确进行初始化。 MSVC 给我错误 expected a '(' or a '{'。我在这里很困惑。如何通过此构造函数正确初始化 _pData 结构?

最佳答案

你应该初始化 _pData 本身,而不是它的成员。例如

Rectangle(Point ulhc, Point lrhc) :
_pData(new RectData{ulhc, lrhc})
{}

关于c++ - 指向用户定义结构的智能指针的成员初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947888/

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