C ++未声明的类错误

时间:2015-03-19 00:34:43

标签: c++ class

我是C ++的新手并且正在尝试学习课程,但却被一些小代码搞砸了。我创建了一个LIBRARYITEM类并给出了错误。我正在使用两个公共函数INPUT()来获取输入,PURCHASE()询问用户他希望购买多少本书。这是代码 -

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    LIBRARYITEM LIBRARYITEM;
    LIBRARYITEM.INPUT();
    LIBRARYITEM.PURCHASE();
}

class LIBRARYITEM
{
public:
    void INPUT();
    void PURCHASE();
private:
    int ITEM_NO;
    char ITEMTITLE;
    float PRICE;
    int TOTALCOAST(int N);
};

void LIBRARYITEM::INPUT() {
    cout << "PLease input item no. - ";
    cin >> ITEM_NO;
    cout << "Please input title- ";
    cin >> ITEMTITLE;
    // We will assume price that per copy is 100$
    PRICE = 100;
}
void LIBRARYITEM::PURCHASE() {
    cout << "How many copies you wish to buy - ";
    int N;
    cin >> N;
    cout << "Total cost for books is - ";
    cout << TOTALCOAST(N);
}

int LIBRARYITEM::TOTALCOAST(int N) {
    return N * PRICE;
}

错误日志是 -

Error   1   error C2065: 'LIBRARYITEM' : undeclared identifier  z:\csci 125\projects\project1\project1\source.cpp   8   1   Project1
Error   2   error C2146: syntax error : missing ';' before identifier 'LIBRARYITEM' z:\csci 125\projects\project1\project1\source.cpp   8   1   Project1
Error   3   error C2065: 'LIBRARYITEM' : undeclared identifier  z:\csci 125\projects\project1\project1\source.cpp   9   1   Project1
Error   4   error C2228: left of '.INPUT' must have class/struct/union  z:\csci 125\projects\project1\project1\source.cpp   9   1   Project1
Error   5   error C2065: 'LIBRARYITEM' : undeclared identifier  z:\csci 125\projects\project1\project1\source.cpp   10  1   Project1
Error   6   error C2228: left of '.PURCHASE' must have class/struct/union   z:\csci 125\projects\project1\project1\source.cpp   10  1   Project1

2 个答案:

答案 0 :(得分:4)

将您的班级声明移至main()之上。 在main()中,声明一个类的实例,尽量不要将该实例(或变量)命名为与类本身相同的名称。

int main()
{
    LIBRARYITEM item;
    item.INPUT();
    item.PURCHASE();
}

答案 1 :(得分:0)

我不知道为什么C ++编译如此愚蠢,只需将main()放在程序结尾就像魅力一样 -

#include <iostream>
#include <iomanip>

using namespace std;


class LIBRARYITEM
{
public:
    void INPUT();
    void PURCHASE();
private:
    int ITEM_NO;
    char ITEMTITLE;
    float PRICE;
    int TOTALCOST(int N);
};

void LIBRARYITEM::INPUT() {
    cout << "PLease input item no. - ";
    cin >> ITEM_NO;
    cout << "Please input title- ";
    cin >> ITEMTITLE;
    // We will assume price that per copy is 100$
    PRICE = 100;
}
void LIBRARYITEM::PURCHASE() {
    cout << "How many copies you wish to buy - ";
    int a;
    cin >> a;
    cout << "Total cost for books is  $ ";
    cout << TOTALCOST(a);
}

int LIBRARYITEM::TOTALCOST(int N) {
    return N * PRICE;
}

int main()
{
    LIBRARYITEM LIBRARYITEM;
    LIBRARYITEM.INPUT();
    LIBRARYITEM.PURCHASE();
    system("pause");
    return 0;
}