【发布时间】:2020-02-14 23:07:16
【问题描述】:
好的,所以我尝试更熟悉 C++ 中的 OOP,我得到了以下代码:
//main.cpp
#include <iostream>
#include "ZooAnimal.h"
using namespace std;
int main()
{
ZooAnimal bozo;
bozo.set_name(12);
// bozo.Create("Bozo", 408, 1027, 400);
// cout << "This animal's name is " << bozo.reptName() << endl;
// bozo.Destroy();
cout << "Hello";
}
//ZooAnimal.h
#ifndef ZOOANIMAL_H
#define ZOOANIMAL_H
class ZooAnimal
{
private:
std::string name;
int cageNumber;
int weightDate;
int weight;
public:
void Create(std::string, int, int, int);
void Destroy();
std::string reptName();
int daysSinceLastWeighted(int today);
void set_name(int);
};
#endif //ZooAnimal
最后,
//ZooAnimal.cpp
#include "ZooAnimal.h"
#include <iostream>
void ZooAnimal::Create(std::string a, int b, int c, int d)
{
//This creates a ZooAnimal Object
name = a;
cageNumber = b;
weightDate = c;
weight = d;
}
int ZooAnimal::daysSinceLastWeighted(int today)
{
//calculate how many days have passed since last weight
return today - weightDate;
}
//clear up the memory
void ZooAnimal::Destroy()
{
delete &name;
}
// return the animal name
std::string ZooAnimal::reptName()
{
return name;
}
void ZooAnimal::set_name(int a)
{
cageNumber = a;
}
所以,当我尝试运行这段代码(当然来自 main.cpp)时,它不会编译,我会在控制台中收到以下消息
C:\Users\<user>\AppData\Local\Temp\ccOiWb7r.o:main.cpp:(.text+0x2e): undefined reference to `ZooAnimal::set_name(int)'
collect2.exe: error: ld returned 1 exit status
我正在使用 MinGW 进行编译,在 Windows 10 机器上工作。奇怪的是,当我尝试在云编辑器(如 repl.it )上运行相同的代码时,它工作得很好,如果我不将我的代码分成多个文件,它再次运行得很好。 知道我能做什么吗?
【问题讨论】:
-
这是整个错误信息吗?
-
旁注:为什么你有一个
Create方法(要求创建没有初始化字段的实例,然后是Createed),而不是使用实际的构造函数?跨度> -
好的,谢谢大家的帮助。问题是我使用 VS 代码编写和一个名为“Code-runner”的扩展来编译项目,但它只构建了 main.cpp 文件,就是这样。在进行了更多挖掘之后,我有了一个名为 Easy C++ 项目的扩展,它似乎工作正常,但我想我可能不得不很快切换到 CLion。非常感谢你们