同一类中的类的静态成员对象 [英] Static member object of a class in the same class

查看:169
本文介绍了同一类中的类的静态成员对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个类为

  class Egg 
{
static Egg e;
int i;
Egg(int ii):i(ii){}
Egg(const Egg&); //防止复制构造函数被调用
public:
static Egg * instance(){return& e}
};

鸡蛋:: e(47);

此代码确保我们不能创建任何对象,但只能使用静态对象。但是我们如何声明类中同一个类的静态对象。



还有一件事,因为e是一个静态对象,静态对象只能调用静态成员函数,因此如何在静态对象e中调用构造函数,并且其构造函数是私有的。

解决方案


但是我们如何声明类中同一个类的静态对象。


A static 成员变量不存储在类的每个对象内。因此,如果在定义类之后在类中声明一个 static 成员变量或作为命名空间级对象,则仅在访问( Class :: var var )并访问 protected

$ <$ p $ <$>


c>是静态对象,静态对象只能调用静态成员函数


我想你正在混合 static 函数和 static 对象。在 static 函数中,只能调用 static 函数(除非你在对象上调用它们)。


那么如何在这里为静态对象调用构造函数 e


对于每个其他对象,也必须为 static 对象调用构造函数。


其构造函数也是私有的


访问控制在C ++中的类级别上检查。因为 static 对象在类中,它可以访问 private 成员。



与其他语言不同,下面是在C ++中合法的,因为访问一个私有成员是从类里面 - 即使是在另一个对象(其他在这种情况下):

  class Test {
private:
int i;
public:
Test(const Test& other)
:i(other.i)
{}
};


Suppose we have a class as

class Egg
{
static Egg e;
int i;
Egg(int ii):i(ii) {}
Egg(const Egg &);    //Prevents copy-constructor to be called
public:
static Egg* instance() {return &e}
};

Egg Egg::e(47);

This code guarantees that we cannot create any object, but could use only the static object. But how could we declare static object of the same class in the class.

And also one thing more since e is a static object, and static objects can call only static member functions, so how could the constructor been called here for static object e, also its constructors are private.

解决方案

But how could we declare static object of the same class in the class.

A static member variable is not stored inside each object of a class. So if you declare a static member variable inside a class or as a namespace level object after you defined the class, differs only in respect to access (Class::var and var) and access to protected and private members.

And also one thing more since e is a static object, and static objects can call only static member functions

I think you are mixing static functions and static objects. Inside a static function you can call only static functions (unless you are calling them on an object).

so how could the constructor been called here for static object e

Like for every other object a constructor has to be called for static objects, too.

also its constructors are private

Access Control is checked on class level in C++. So since the static object is inside the class, it can access private members.

Unlike in some other languages, the following is legal in C++, since the access to a private member is from inside the class - even if on another object (other in this case):

 class Test {
 private:
      int i;
 public:
      Test(const Test &other)
      : i(other.i)
      {}
 };

这篇关于同一类中的类的静态成员对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆