C ++中的等效标识符

时间:2013-03-01 20:10:37

标签: java c++

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

我想知道在C ++中是否存在类似于公共私有等的标识符,就像在java中一样。因为我知道

在Java中

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

在C ++中

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

6 个答案:

答案 0 :(得分:5)

在C ++中,您不会将访问说明符应用于Java中的单个声明。您可以在类中的各个部分进行设置,直到下一个访问说明符的所有成员都具有该访问级别。

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

答案 1 :(得分:4)

有,但仅限于班级范围。在引用成员时,它们定义整个部分,而不是单独应用于每个成员:

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 ++中没有模块的概念)。如果一个类嵌套在另一个类中,则它只能是private / protected。

答案 2 :(得分:4)

在C ++中有public / private / protected“sections”:

class A
{
private:
    string a;
    void M1();

protected:
    string b;
    void M2();

public:
    string c;
    void M3();
};

答案 3 :(得分:3)

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;
};

答案 4 :(得分:0)

在C ++中

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

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

取决于您是否需要字符数组或字符串对象。

答案 5 :(得分:0)

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

例如

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

private:
 int y;
};

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