【问题标题】:What is wrong with this simple C++ class program? [closed]这个简单的 C++ 类程序有什么问题? [关闭]
【发布时间】:2016-10-20 19:46:46
【问题描述】:

请帮助我是 C++ 初学者 我找不到合适的解决方案。我还在这个问题中添加了错误图片。请给我正确的解决方案。

#include <iostream>
#include <conio.h>

class test
{
    int no;
    static int count;
    public:
        void getval (int);
        void dispcount (void);

};

void test:: getval(int x)
{
    no = x;
    cout << "Number = " << no << endl;;
    count++;
}

void test::dispcount(void)
{
    cout << "Counten = " << count;
}
    int test::count;

int main()
{
    test t1,t2,t3;

    t1.dispcount();
    t2.dispcount();
    t3.dispcount();

    t1.getval(100);
    t2.getval(200);
    t3.getval(300);

    t1.dispcount();
    t2.dispcount();
    t3.dispcount();
    getch();
    return 0;
}

here is error.jpg

【问题讨论】:

  • 为了找到合适的解决方案,您需要找出问题所在。你这样做了吗?
  • 不要在问题中包含难以阅读的图像,例如,在您的问题中。您必须以纯文本形式包含错误消息。作为 C++ 初学者,您需要学习的最佳技能是如何以其他人都能理解您的方式交流您的问题。
  • 使用std::cout &lt;&lt; ...
  • 你没有放图片,无论如何你应该将完整的错误信息发布为文本而不是图像
  • “图片已添加”,因为人们告诉您不要发布图片。淘气。

标签: c++ class namespaces


【解决方案1】:

包含指令

#include <iostream>
#include <conio.h>

using namespace std;
//..

或者包括使用声明,如

#include <iostream>
#include <conio.h>

using std::cout;
using std::endl;
//...

或者使用限定名例如

void test:: getval(int x)
{
    no = x;
    std::cout << "Number = " << no << std::endl;
    ^^^^^^^^^                         ^^^^^^^^^^
    count++;
}

标识符 coutendl 在命名空间 std 中声明,而不是在全局命名空间中。

【讨论】:

  • 初级 C++ 程序员不应该真正接触到bad programming habits like "using namespace std;"
  • @SamVarshavchik 我确信他们开始使用 using 指令学习 C++。无论如何,任何程序员都应该知道所有的可能性。
  • 你很棒.....
  • @KamalMrock 你应该适当地初始化 test::count ,因为你在没有初始化的情况下在 t1.dispcount() 中使用它,这会给出一个警告设置它等于 0
  • @MekacherAnis 被编译器初始化为0,作为一个静态存储时长的对象。
猜你喜欢
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 2012-12-31
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多