gpt4 book ai didi

C++ - 这个单独的编译代码有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 15:35:11 24 4
gpt4 key购买 nike

<分区>

我正在尝试调试这段代码。我觉得没问题。但是我得到一个我不明白的错误。这是我的代码

//struct.h
#ifndef STRUCT_H
#define STRUCT_H
#include <iostream>
using namespace std;

struct Person {
Person();
Person(int a, string n);
Person(const Person &p);
Person &operator=(const Person &p);
~Person();
int age;
string name;
};

#endif

//struct.cc
#include "struct.h"

Person::Person(): age(0), name("noname") {
cout << "Creating default Person" << endl;
}

Person::Person(int a, string n): age(a), name(n) {
cout << "Creating: " << name << "," << age << endl;
}

Person::Person(const Person &p) {
name = p.name;
age = p.age;
}

Person& Person::operator=(const Person &p) {
Person person;
person.name = p.name;
return person;
}

Person::~Person() {
cout << "Destroying: " << name << "," << age << endl;
}

//structMain.cc
#include "struct.h"
#include <iostream>
using namespace std;

int main() {
Person one(21, "Zuhaib");
cout << "I am " << one.name << ". I am " << one.age << " years old" << endl;

Person two;
cout << "I am " << two.name << ". I am " << two.age << " years old" << endl;

two = one;
cout << "I am " << two.name << ". I am " << two.age << " years old" << endl;
}

我用

编译
g++ -c struct.cc 
g++ -c structMain.cc

g++ -o struct.o structMain.o

然后我得到以下错误

structMain.o: In function `main':
structMain.cc:(.text+0x3b): undefined reference to `Person::Person(int, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
structMain.cc:(.text+0xb5): undefined reference to `Person::Person()'
structMain.cc:(.text+0x11e): undefined reference to `Person::operator=(Person const&)'
structMain.cc:(.text+0x180): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x18c): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x1b8): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x1e3): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x1f4): undefined reference to `Person::~Person()'
collect2: ld returned 1 exit status

我想我包含了所有正确的文件。我仔细检查了声明和定义。我只是不确定为什么会出现这些错误。我觉得不错。

另外,在main函数中,行发生了什么

two = one;

我想知道这是因为,我重载了 operator=,但我还定义了复制构造函数,它在遇到“=”时也会执行。所以在上面的例子中,operator= 执行的还是复制构造函数。任何帮助,将不胜感激。谢谢

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