【问题标题】:Why isn't this program compiling [closed]为什么这个程序不编译[关闭]
【发布时间】:2014-02-02 14:33:40
【问题描述】:
#include <iostream>
class Abc // created class with name Abc
{
    void display()//member function
    {
        cout<<"Displaying NO."<<endl;
    }
};
int main()
{
    Abc obj;//creating object of the class
    obj.display();//calling member function inside class
}

它返回错误

main.cpp: In function 'int main()':
main.cpp:5:10: error: 'void Abc::display()' is private
     void display()
          ^
main.cpp:13:17: error: within this context
     obj.display();
                 ^

我试图让显示功能public int main 但随后它给出了错误

main.cpp:5:11: error: expected ':' before 'void'
    public void display()
           ^

【问题讨论】:

  • 错误消息是非常描述性的。 class 中的默认访问说明符是 private
  • 彻底阅读书籍,不要只是看一眼就开始编程

标签: c++


【解决方案1】:

声明为:

class Abc
{
public:

    void display()
    {
        cout<<"Displaying NO."<<endl;
    }
};

或:

struct Abc
{
    void display()
    {
        cout<<"Displaying NO."<<endl;
    }
};

struct的默认保护是public,class的默认保护是private

【讨论】:

  • 或者把Abc改成struct;)
【解决方案2】:

错误信息很清楚。您不得在类外调用私有成员函数。默认情况下,带有关键字 class 的类默认具有私有访问控制。要么写

class Abc // created class with name Abc
{
public:
 void display()//member function
    {
        cout<<"Displaying NO."<<endl;
    }
};

struct Abc // created class with name Abc
{
 void display()//member function
    {
        cout<<"Displaying NO."<<endl;
    }
};

带有关键字 struct 的类默认具有公共访问控制。

另外最好将成员函数定义为

 void display() const//member function
 {
        std::cout<<"Displaying NO."<<endl;
 }

考虑到你没有使用directibe

using namespace std;

您必须对在 std:: 中声明的实体使用限定名称。例如

        std::cout<<"Displaying NO."<<std::endl;

【讨论】:

  • 你能告诉我下面这行有什么用吗:using namespace std;
  • endl 也是std 的一部分
  • @Paranaix 谢谢,我更新了我的帖子。
  • @vivek321 标头 中声明的所有名称都属于命名空间 std::。该指令告诉编译器,如果它遇到 cout 这样的名称,它还必须查看此标头中声明的名称。
猜你喜欢
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多