我正在定义一个函数来将元素添加到 vector<Point> original_points
,名为
void add_point()
.为什么要突出显示 original_points
作为 undefined,在函数体中,当我使用 type qualifier: friend(获得访问权限)并且它在 类(class)?
// data structure representing Point in 2D plane
class Point{
public:
//contructors
Point();
Point(double x, double y);
// non-modifying methods
inline double get_xcoord()const{return xcoord;}
inline double get_ycoord()const{return ycoord;}
// modifying methods
inline double set_xcoord(double x){xcoord=x;}
inline double set_ycoord(double y){ycoord=y;}
// non-member function with access to private members
friend inline void add_point(const Point& p){original_points.push_back();}
private:
double xcoord;
double ycoord;
vector<Point> original_points;};
我做错了什么?
最佳答案
至少存在三个主要问题:
首先,std::vector::push_back()
有一个参数。你需要传递一个 Point
实例给它。看来你想添加 p
:
original_points.push_back(p);
第二,友元函数是非成员函数,因此如果没有该类的实例,则无法通过它访问该类的成员。你没有这样的实例,所以你的 friend 功能没有意义。这会编译,但不会有任何效果:
friend
inline void add_point(const Point& p){
Point x;
x.original_points.push_back(p);
}
也许你想要add_point()
成为成员(member),在这种情况下它不应该是 friend
.这将解决第二个问题,但是...
第三,假设original_points
是一个 std::vector<Point>
,这样的容器不能用不完整的类型实例化。所以Point
不能有数据成员 std::vector<Point>
无需调用未定义的行为。另一方面,如果它是 boost::container::<Point>
, 或另一个 vector
支持不完整类型,那很好。
总而言之,您的代码似乎很糟糕。
关于c++ - 类范围和私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29433502/