我有一个小oop程序,我不知道为什么它不会编译

时间:2015-08-05 15:11:32

标签: c++ oop

以下是代码:

#include <iostream>
#include <string>
using namespace std;

int main(){
  Oseba akk("kreso");
  akk.printing();
}

class Oseba{
public:
  string Ime;

  Oseba(){}

  Oseba(string _Ime){
    Ime=_Ime;
  }

  void printing(){
    cout << Ime << endl;
  }
};

这些是错误:

error C2065: 'Oseba' : undeclared identifier
error C2146: syntax error : missing ';' before identifier 'akk'
error C3861: 'akk': identifier not found
error C2065: 'akk' : undeclared identifier
error C2228: left of '.Izpis' must have class/struct/union

3 个答案:

答案 0 :(得分:2)

您正在使用在main之后定义的类。在main之前定义你的类,它在编译时解决了错误。

 #include <iostream>
 #include <string>
 using namespace std;


class Oseba{
public:
    string Ime;

    Oseba(){}

    Oseba(string _Ime){
        Ime=_Ime;
    }

    void printing(){
        cout << Ime << endl;
    }
};

int main(){
    Oseba akk("kreso");
    akk.printing();
}

答案 1 :(得分:2)

您发现这些错误是因为函数已在main函数之前声明:

#include <iostream>
#include <string>
using namespace std;


class Oseba{
public:
    string Ime;

    Oseba(){}

    Oseba(string _Ime){
        Ime=_Ime;
    }

    void printing(){
        cout << Ime << endl;
    }
};

int main(){
    Oseba akk("kreso");
    akk.printing();
}

答案 2 :(得分:0)

编译器不知道Oseba akk("kreso");是什么。原因是因为源文件从上到下解释。

您需要在int main()之前声明该类,或者将该类放入另一个文件中,然后包含该文件。