“class:”在c++中是什么意思?

时间:2023-01-18 16:55:29

I've never seen it before. I thought it was a typo for "::sample", but when I saw it actually compiles I was very confused. Can anyone help me find out please? I don't think it's a goto label.

我以前从未见过。我认为它是“::sample”的打印错误,但当我看到它实际编译时,我非常困惑。谁能帮我查一下吗?我不认为这是一个goto标签。

void f() {
  class: sample {
    // there were some members declared here
  } x;
}

3 个解决方案

#1


79  

It is an unnamed class, and the colon means it inherits privately from sample. See it like

它是一个未命名的类,冒号表示它私有地从sample继承。看到它就像

class Foo : private sample
{
    // ...
};

Foo x;

#2


21  

I think that is defining an unnamed class deriving from sample. And x is a variable of that unnamed class.

我认为这定义了一个从sample派生的未命名类。x是这个未命名类的一个变量。

struct sample{ int i;};

sample f() 
{
  struct : sample 
  {
    // there were some members declared here
  } x;
  x.i = 10;
  return x;
}
int main() 
{
        sample s = f();
        cout << s.i << endl;
        return 0;
}

Sample code at ideone : http://www.ideone.com/6Mj8x

示例代码见ideone: http://www.ideone.com/6Mj8x

PS: I changed class to struct for accessibility reason!

PS:由于可访问性的原因,我把类改成了struct !

#3


1  

That's an unnamed class.

这是一个匿名类。

You can use them e.g. to substitute for local functions in pre-C++11:

你可以用它们来代替pre- c++ 11中的本地功能:

int main() {
    struct {
        int operator() (int i) const {                 
            return 42;
        }
    } nice;

    nice(0xbeef);
}

The colon followed by sample simply means derive from sample using default inheritance. (for structs: public, for classes: private)

冒号后面是样本,简单地说就是使用默认继承的样本。(用于结构:public, for classes: private)

#1


79  

It is an unnamed class, and the colon means it inherits privately from sample. See it like

它是一个未命名的类,冒号表示它私有地从sample继承。看到它就像

class Foo : private sample
{
    // ...
};

Foo x;

#2


21  

I think that is defining an unnamed class deriving from sample. And x is a variable of that unnamed class.

我认为这定义了一个从sample派生的未命名类。x是这个未命名类的一个变量。

struct sample{ int i;};

sample f() 
{
  struct : sample 
  {
    // there were some members declared here
  } x;
  x.i = 10;
  return x;
}
int main() 
{
        sample s = f();
        cout << s.i << endl;
        return 0;
}

Sample code at ideone : http://www.ideone.com/6Mj8x

示例代码见ideone: http://www.ideone.com/6Mj8x

PS: I changed class to struct for accessibility reason!

PS:由于可访问性的原因,我把类改成了struct !

#3


1  

That's an unnamed class.

这是一个匿名类。

You can use them e.g. to substitute for local functions in pre-C++11:

你可以用它们来代替pre- c++ 11中的本地功能:

int main() {
    struct {
        int operator() (int i) const {                 
            return 42;
        }
    } nice;

    nice(0xbeef);
}

The colon followed by sample simply means derive from sample using default inheritance. (for structs: public, for classes: private)

冒号后面是样本,简单地说就是使用默认继承的样本。(用于结构:public, for classes: private)