指向用户定义结构的智能指针的成员初始化列表
Member initialization list for smart pointer to user-defined struct
下面是程序。它只是一个基于 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})
{}
下面是程序。它只是一个基于 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})
{}