简体   繁体   English

C ++:我无法启动我的课程,我在这个范围错误中未声明课程

[英]C++: I can't start my class, I get class was not declared in this scope error

I'm using netbeans with gcc compiler and when I try to declare an object of my class, and run the code I get the class was not delclared in this scope error, this is my code in main.cpp: 我在gcc编译器中使用了netbeans,当我尝试声明类的对象并运行代码时,我得到的类未在此作用域错误中声明,这是我在main.cpp中的代码:

#include <cstdlib>
#include <iostream>
#include <cstring>

using namespace std;

int main() {
    Clock r;
    r.processH();

    return 0;
}

class Clock {

private:
    int h, m, s;
    char conv[];

    Clock() {
        h = 0;
        m = 0;
        s = 0;
        conv[10] = {};
    }

public:

    void processH() {
        int r =0; 
        while(r <= 2){
            conv[r] = 'I';
            if(conv == "III") {
                conv[0] = 'V';
                conv[1] = 'I';
                r++;
                break;
            }
            r++;
        }
        cout<< r;
    }

};

What am I doing wrong? 我究竟做错了什么? I'm not an experienced OOP programmer. 我不是经验丰富的OOP程序员。

First, you should declare the class before you use it's name. 首先,您应该在使用类的名称之前对其进行声明。 In your case it should be above the main function. 在您的情况下,它应该位于main功能之上。

Second, you declared Reloj function with no return type, which is illegal. 其次,您声明的Reloj函数没有返回类型,这是非法的。

The correct code may look like this: 正确的代码如下所示:

#include <cstdlib>
#include <iostream>
#include <cstring>

using namespace std;

class Clock {
private:
    int h, m, s;
    char conv[];

    void Reloj() {
        h = 0;
        m = 0;
        s = 0;
        conv[10] = {};
    }

public:

    void processH(int ent) {
        int r =0; 
        while(r <= 2) {
            conv[r] = 'I';
            if(conv == "III") {
                conv[0] = 'V';
                conv[1] = 'I';
                r++;
                break;
            }
            r++;
        }
        cout<< r;
    }
};


int main() {
    Clock r;
    r.processH(5);
    return 0;
}

Just a complement to Sergey's answer : You could also forward declare the class. 只是对Sergey的回答的补充:您还可以向前声明该类。 Just add the line 只需添加行

class Clock;

before your main function to tell the compiler that the class exists. 在您的main功能告诉编译器该类存在之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM