c++中的等效标识符

equivalent identifiers in C++

本文关键字:标识符 c++      更新时间:2023-10-16

我是一个编程新手,我有一个简单的疑问。

我想知道是否有一个等效的标识符,如公共,私有等在c++中,如目前在java中。for ex I know

在Java中

*public String small(){
return "hello";
}*
在c++

*string small(){
return "hello";
}*

在c++中,不像在Java中那样对单个声明应用访问说明符。您可以在类中的节中设置它们,并且直到下一个访问说明符的所有成员都具有该访问级别。

class MyClass {
public:
    std::string small() const { return "hello"; }
    int also_public();
private:
    void another_func();
};

c++中有公共/私有/受保护的"sections":

class A
{
private:
    string a;
    void M1();
protected:
    string b;
    void M2();
public:
    string c;
    void M3();
};

有,但仅限于类范围。当引用成员时,它们定义整个section,而不是单独应用于每个成员:

class Foo : public Bar // public inheritance. Can be private. Or even protected!
{
 public:.
  int a; // public
  double b; // still public
 private:
  double x; // private
 public:
  double y; // public again:
 protected:
  // some protected stuff
};

访问说明符不适用于类(c++中也没有模块的概念)。只有当一个类嵌套在另一个类中时,它才能是私有的/受保护的。

c++有可访问性修饰符,但与Java不同,您不必在每个成员上重复它们:

class C
{
    int a; // private, since class members are private by default
public:
    int b; // public, since it's in a block of public members
    int c; // also public
private:
    int d; // private again
protected:
    int e; // protected
};
struct S
{
    int a; // public, since struct implicitly gives a block of public members
public:
    int b; // public, since it's in a block of public members
    int c; // also public
private:
    int d; // private again
protected:
    int e; // protected
};

顺便说一下,由可访问性标签创建的块不仅控制访问,而且影响内存布局。

这个类是标准布局POD:

struct S
{
    int a;
    int b;
    int c;
};

struct S
{
private:
    int a;
    int b;
    int c;
};

但这不是:

struct S
{
    int a;
    int b;
private:
    int c;
};

这个是在c++ 11中,而不是在c++ 03中:

struct S
{
    int a;
    int b;
public:
    int c;
};

in c++

const char *small() {
    return "hello";
}

std::string small() {
    return "hello";
}

取决于你是想要一个字符数组还是一个字符串对象

可以在c++类中使用public, private和protected。

例如

Class A {
public:
 int x;
 int getX() { return x; }
private:
 int y;
};

这里的x和getX函数是公共的。y是私有的。