C++ 中类的定义

Definition of class in c++

本文关键字:定义 C++      更新时间:2023-10-16

有人可以向我解释为什么这个例子不起作用吗?我真的不知道问题出在哪里。

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

提前谢谢你。

您收到的错误说类 testtest的方法private 。这是因为 class 的默认访问修饰符是 private(对于struct,它是 public )。因此,如果您在class中声明了一些成员或方法,并且没有明确指定访问修饰符(publicprotectedprivate),那么默认情况下它将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:"即可。

构造函数和所有其他成员函数在您的类中都是私有的 你必须写公开:在写他们的胭视之前!