C++ 中类的定义
Definition of class in c++
有人可以向我解释为什么这个例子不起作用吗?我真的不知道问题出在哪里。
class test{
test();
test(const int n);
void show();
private:
int number;
};
test::test(const int n){
number = n;
}
void test::show(){
cout << number << endl;
}
int main(int argc, char** argv) {
test a(10);
return 0;
}
以下是错误:
main.cpp:33:1: error: ‘test::test(int)’ is private
test::test(const int n){
^
main.cpp:43:14: error: within this context
test a(10);
提前谢谢你。
您收到的错误说类 test
中test
的方法private
。这是因为 class
的默认访问修饰符是 private
(对于struct
,它是 public
)。因此,如果您在class
中声明了一些成员或方法,并且没有明确指定访问修饰符(public
、protected
、private
),那么默认情况下它将private
。
只需更改:
class test{
test();
test(const int n);
void show();
private:
int number;
};
自:
class test{
public: // <--- THIS
test();
test(const int n);
void show();
private:
int number;
};
在C++中,类成员和方法的默认访问限定符是 private
。换句话说,如果您不指定一个,这就是您所做的,它将默认为 private
.几行后定义另一个private
段的事实不会改变这一点。因此,您需要做的是在类定义开始时添加一个public
段,它将按预期工作。
相反,如果您使用的是struct
而不是class
,则相反。
首先,
默认情况下,你写在类体内的所有成员都是私有的,除非你指定了公共的,受保护的。 因此,在您的情况下,成员函数是私有的,您需要在需要在类外部访问的函数之前将访问限定符指定为 public。
访问修饰符有助于实现封装。
此外,您可以访问类内的私有成员,但不能访问类外,除非您使用好友函数。
class test{
private:
int number; //private member, Note: if I remove private from above this variable will still be private because by default it is private
public:
test();//default constructor
test(const int n);//parametrized constructor
void show()const;//show/display function, its better if you put const, this cannot modify your data member of your class
};
test::test(const int n)
{
number = n;
}
void test::show()
{
cout << number << endl;
}
int main(int argc, char** argv)
{
test a(10);
return 0;
}
谢谢。
默认情况下,类成员是私有的,因此所有成员都是私有的,底部的"private:"子句是多余的。只需在"类测试 {"之后添加"public:"即可。
构造函数和所有其他成员函数在您的类中都是私有的 你必须写公开:在写他们的胭视之前!
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- 如何确保C++函数在定义之前声明(如override关键字)
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在命名空间中定义函数还是限定函数
- 此代码是否违反一个定义规则
- 编译C++时未定义的引用
- 不同翻译单元中不可重载的非内联函数定义
- 为什么在定义函数之前先声明它
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何定义一个纯抽象基类