我正在尝试理解我所举示例中的命名构造函数习语
点.h
class Point
{
public:
static Point rectangular(float x, float y);
private:
Point(float x, float y);
float x_, y_;
};
inline Point::Point(float x, float y) : x_(x), y_(y) {}
inline Point Point::rectangular(float x, float y) {return Point(x,y);}
主要.cpp
#include <iostream>
#include "include\Point.h"
using namespace std;
int main()
{
Point p1 = Point::rectangular(2,3.1);
return 0;
}
如果 Point::rectangular
不是 static
,它不会编译,我不明白为什么...
最佳答案
在此上下文中,函数前面的 static
关键字表示此函数不属于该类的任何特定实例。普通类方法有一个隐式的 this
参数,允许您访问该特定对象的成员。但是 static
成员函数没有隐式的 this
参数。本质上,静态函数与自由函数相同,除了它可以访问它在其中声明的类的 protected 成员和私有(private)成员。
这意味着您可以在没有该类实例的情况下调用静态函数。而不是需要类似的东西
Point p1;
p1.foo();
你只需这样做:
Point::foo();
如果你试图像这样调用一个非静态函数,编译器会报错,因为非静态函数需要一些值来分配给隐式的 this
参数,而 Point::foo()
不提供这样的值。
现在您希望 rectangular(int, int)
为静态的原因是因为它用于从头开始构造新的 Point
对象。您不需要现有的 Point
对象来构造新点,因此声明函数 static
是有意义的。
关于c++ - 为什么我必须把这个函数静态化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15077168/