【问题标题】:class issue in C++C++ 中的类问题
【发布时间】:2012-04-03 12:01:09
【问题描述】:

我在家具.h 中有这个:

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

class Furniture {
public:
    Furniture();
    virtual ~Furniture();
    void setname(string name);
    void setprice(double price);
    int getprice();
    string getname();
private:
    string name;
    int price;
protected:
    static int NumberOfItems;
    int Id;

}

还有这个在家具.cpp中

#include "furniture.h"

void Furniture::setname(string name) {
    this->name = name;
}
string Furniture::getname()
{
    return this->name;
}
void Furniture::setprice(double price) {
    this->price = price;
}
int Furniture::getprice() {
    return this->price;
}

int main() {
    Furniture *model = new Furniture();
    model->setname("FinalDestiny");
    model->setprice(149.99);
    cout<<"Model name: "<<model->getname()<<" - price = "<<model->getprice();
}

但我收到一些错误,例如:

错误 1 ​​错误 C2628: 'Furniture' 后跟 'void' 是非法的(你忘记了 ';' 吗?) c:\final\facultate\poo\laborator 1\furniture.cpp 3 1 POO_lab

错误 2 错误 C2556: 'Furniture Furniture::setname(std::string)' : 重载函数的不同之处仅在于返回类型来自 'void Furniture::setname(std::string)' c:\final\facultate\便便\laborator 1\furniture.cpp 3 1 POO_lab

错误 3 错误 C2371: 'Furniture::setname' : 重新定义;不同的基本类型 c:\final\facultate\poo\laborator 1\furniture.cpp 3 1 POO_lab

错误 5 错误 C2264: 'Furniture::setname' : 函数定义或声明错误;未调用函数 c:\final\facultate\poo\laborator 1\furniture.cpp 19 1 POO_lab

我做错了什么?

【问题讨论】:

  • 错误 1 ​​错误 C2628: 'Furniture' 后跟 'void' 是非法的(你忘记了 ';' 吗?)

标签: c++ oop class methods


【解决方案1】:

您在头文件中的类定义末尾缺少;

// ...snipped...

protected:
    static int NumberOfItems;
    int Id;

}; // <-- here

【讨论】:

    【解决方案2】:

    您在类定义的末尾忘记了一个分号。

    // ...
    protected:
        static int NumberOfItems;
        int Id;
    }; // <--
    

    我讨厌 C++ :)

    【讨论】:

    • @JerryCoffin:谢谢,已修复。你知道,你可以随时编辑它;)
    【解决方案3】:

    两件事;

    • 您没有以; 结束您的类定义,您需要在家具.h 末尾添加一个。

    • 您已声明有构造函数和析构函数,但您的 .cpp 文件中都没有实现。

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2011-01-27
      相关资源
      最近更新 更多