c++中的等效标识符
equivalent identifiers in C++
我是一个编程新手,我有一个简单的疑问。
我想知道是否有一个等效的标识符,如公共,私有等在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是私有的。
相关文章:
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- #ifdef和未声明的标识符
- f2、f3、f4标识符未找到
- 设置 Visual Studio for MPI: 找不到标识符错误
- 未声明的标识符编译暗黑破坏神 2 程序"muleview"
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- Google protobuf 时间戳未声明标识符,在 Windows 上具有C++
- 如何让 GCC/Clang 在保留标识符上出错
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 当简单捕获中的标识符显示为参数的声明符 ID 时,没有编译器诊断
- 使用说明符 extern 声明的C++中的标识符链接
- C++:枚举:错误:应使用标识符而不是"}"
- 为什么我们不能重复使用具有不同模板参数的别名模板标识符?
- Visual Studio C++ PlaySound 标识符未定义
- 为什么我们不编写可以处理C++标识符的汇编器和链接器?
- 使用未声明的标识符"sqrt"?
- 找不到标识符合并
- 在模板化函数中重新定义(忽略)的 SWIG 标识符
- 在 c++ 中找不到此函数的标识符
- 对类 (C++) 中的私有变量使用未声明的标识符