提问人:DantesExile 提问时间:3/25/2021 更新时间:4/5/2021 访问量:1218
C++ 错误:初始化类对象时未定义引用
C++ Error: Undefined Reference When Initializing a Class Object
问:
这是我进入 C++ 世界的第一步。我正在试验一个使用类的简单程序。该程序是提示用户输入用户名和年龄,然后使用给定数据创建一个类对象,然后返回 greet 方法,该方法接受 Person 的类对象并返回问候语。但是,当我尝试构建到程序时,出现以下错误:
“C:\Program Files\mingw-w64\x86_64-8.1.0-posix-she-rt_v6-rev0\mingw64\bin\g++.exe” -g “D:\OOP 实验室和作业\Lab5\lab5.cpp” -o “D:\OOP 实验室和作业\Lab5\lab5.exe” C:\Users\okii_\AppData\Local\Temp\cc1mDRfr.o:在函数 Person::P erson(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int)' collect2.exe:错误:ld 返回 1 退出状态
main': D:/OOP Labs and Assignments/Lab5/lab5.cpp:21: undefined reference to
生成已完成,但出现错误。 终端进程无法启动(退出代码:-1)。
我将其追溯到错误发生的位置,当我尝试创建对象时,它似乎正在发生。我不知为什么会出现此错误。任何指导将不胜感激。我正在使用 Visual Studio Code 和 g++ 来编译我的代码,我的文件如下。
Person.hpp:
#ifndef PERSON_HPP
#define PERSON_HPP
#include <string>
class Person
{
private:
// private section: private class members will be added here
std::string name;
int age;
public:
//pulic section: public class memeber will be added here
// Constructor
// Parameter theName: the name of the person
// theAge: the age of the person
Person(const std::string & theName, int theAge);
// Get the name of the person, returned as a constant reference.
const std::string & getName() const;
// Get the age of the person
int getAge() const;
// Set age of the person
void setAge(int value)
{
this->age = value;
}
};
#endif
人员.cpp:
#include "Person.hpp"
using namespace std;
Person::Person(const string & theName, int theAge)
: name{theName}, age{theAge}
{} // empty body constructor
const string & Person::getName() const
{
return name;
}
int Person::getAge() const
{
return age;
}
lab5.cpp
#include <iostream>
#include "Person.hpp"
using namespace std;
void greet(const Person & p);
int main()
{
string userName;
int userAge;
cout << "Enter your name: ";
cin >> userName;
cout << "Enter your age: ";
cin >> userAge;
Person thePerson(userName, userAge);
greet(thePerson);
}
void greet(const Person & p)
{
string name = p.getName();
int age = p.getAge();
cout << "Hello " << name;
cout << "Your age is " << age;
}
tasks.json文件:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: \"C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe\""
}
]
}
答:
正如 Drew 和 Useless 所指出的,我需要先编译我的程序来解决错误。我编译了程序,它运行得很顺利。
评论
Person::Person(const string &, int)
lab5.cpp
lab5.exe
Person.cpp
lab5.o
.obj
Person.o