gpt4 book ai didi

c++ - 未定义对 Classname::Classname() 的引用和其他错误

转载 作者:行者123 更新时间:2023-11-30 01:11:48 28 4
gpt4 key购买 nike

这是一个菜鸟问题,抱歉,我来自 Java,不知道为什么我的 OO 东西不起作用。我有这个主要的:

#include <iostream>
#include "Foo.h" //changed name
using namespace std;

int main(int argc, char*argv[])
{
int choice;
cin >> choice;

Foo net;
switch(choice)
{
case 1: net.buildNetwork(); break;
}
}

这个Foo.h 文件:

#ifndef FOO_H
#define FOO_H
#include <iostream>
struct City{
std::string cityName;
std::string message;
City *next;

City(){}; // default constructor

City(std::string initName, City *initNext, std::string initMessage)
{
cityName = initName;
next = initNext;
message = initMessage;
}

};

class Foo
{
public:
Foo();
~Foo();
void addCity(std::string, std::string);
void buildNetwork();
void transmitMsg(char *); //this is like a string
void printNetwork();
protected:
private:
City *head;
City *tail;
};

#endif // FOO_H

还有这个 Foo.cpp 文件,都在同一个目录中:

#include "Foo.h"
#include <iostream>
using namespace std;

Foo::Foo()
{
head = tail = NULL;
}

Foo::~Foo(){}

void Foo::buildNetwork()
{
cout << "works" << endl;
}
void Foo::transmitMsg(){}
void Foo::printNetwork(){}
void Foo::addCity(){}

当我编译时,我得到

/tmp/ccNx3fY5.o: In function `main':
main.cpp:(.text+0x38): undefined reference to `Foo::Foo()'
main.cpp:(.text+0x4c): undefined reference to `Foo::buildNetwork()'
main.cpp:(.text+0x59): undefined reference to `Foo::~Foo()'
main.cpp:(.text+0x7e): undefined reference to `Foo::~Foo()'
collect2: error: ld returned 1 exit status

怎么了?另外,还有一个问题:在 Foo.cpp 中,为什么我需要 Foo::Foo() 等?我使用了 namespace std,那为什么我不能直接说 Foo()

最佳答案

看你编译的方式,你只提供了一个源文件(main.cpp),而正确的方法是指定所有的源文件。在您的情况下,它将是:

g++ main.cpp foo.cpp -o executable

“ undefined reference ”错误是在链接器无法正确解析名称时在链接阶段抛出的错误,因为您没有像上面那样正确链接源文件。

此外,请确保在声明函数原型(prototype)时,函数的实现也应具有相同的签名。在您的示例中,您将函数原型(prototype)提供为:

void transmitMsg(char *);
void addCity(std::string, std::string);

但是您对这些函数的实现没有正确的签名。他们应该是:

void Foo::transmitMsg(char *){}

void Foo::addCity(std::string, std::string){}

why do I need Foo::Foo() etc?

因为 Foo() 是类 Foo 的函数。

I used namespace std, so why can't I just say Foo()?

当您调用 using namespace 时;该命名空间中的所有符号都将在不添加命名空间前缀的情况下变得可见。符号可以是函数、类或变量。

Foo 不是像“std”这样的命名空间。它是一个用户定义的类。

关于c++ - 未定义对 Classname::Classname() 的引用和其他错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283773/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com