0
点赞
收藏
分享

微信扫一扫

c++基础(构造函数)

构造函数是创建类实例时候对实例进行初始化,做一些实例的个性事情,类(型)更像表单,模板。具体的内容还是需要实例根据自己实际情况进行定制。
构造函数定义是他是一个类名称作为方法名的方法,如果类设计者没有定义构造函数,编译器会自动生成一个空的构造函数,所谓的空就是这个构造函数没有参数也没有返回值,函数体中什么都没有做。

class Pointer
{
  public:
    float x, y;

    void Position()
    {
        std::cout << x << y << std::endl;
    }
};

int main(int argc, char const *argv[])
{
    Pointer p;
    p.Position();
    std::cin.get();
}

下面我们可以给 Player 类添加一个构造函数来初始化其属性 x,y

class Pointer
{
  public:
    float x, y;

    Pointer(float x, float y)
    {
        x = x;
        y = y;
    }

    void Position()
    {
        std::cout << x << y << std::endl;
    }
};
Pointer p(10, 10);

当然我们通过 private 来修饰构造函数来限制对类进行实例化,让使用者调用类的静态方法。

class Tut
{

  public:
    Tut() = delete;

    static void Print()
    {
        std::cout << "angular basic tut by zidea" << std::endl;
    }
};

int main(int argc, char const *argv[])
{

    Tut::Print();

    Tut t;
举报

相关推荐

0 条评论