编译c++教程(programmingHelp.org)时出错

Error compiling c++ tutorial (programmingHelp.org)

本文关键字:出错 org programmingHelp c++ 教程 编译      更新时间:2023-10-16

我正在关注youtube上的教程。我似乎遇到了一个自己无法解决的错误。目标是创建一个名为BMI的类,它将用户的体重名称和身高打印出来。。

我正试图用g++编译它,我怀疑我做得不对。通常我只做g++文件名.cpp,在这种情况下我应该这样做吗?

本教程最初是在微软。。。。东西,我不知道它的名字。对不起

谢谢,代码附在下面。

错误

/tmp/ccRcewk3.o: In function `main':
Main.cpp:(.text+0x7d): undefined reference to `BMI::BMI()'
Main.cpp:(.text+0x89): undefined reference to `BMI::getWeight() const'
Main.cpp:(.text+0x9a): undefined reference to `BMI::getHeight() const'
Main.cpp:(.text+0xaf): undefined reference to `BMI::getName() const'
Main.cpp:(.text+0x14f): undefined reference to `BMI::~BMI()'
Main.cpp:(.text+0x184): undefined reference to `BMI::~BMI()'
collect2: ld returned 1 exit status

主要.cpp

#include <iostream>
#include <string>
#include "BMI.h"
using namespace std;
/**************************************************/
int main()
{
string name;
int height;
double weight;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your height (cm): ";
cin >> height;
cout << "Enter your weight (kg): ";
cin >> weight;
BMI Student_1;
cout << endl << "Patient name: " << Student_1.getName() << endl <<
"Height: " << Student_1.getHeight() << endl <<
"Weight: " << Student_1.getWeight() << endl;
return 0; 
}
/**************************************************/

BMI.h

// Header ==> Function Declarations
#include <iostream>
#include <string>
using namespace std;
// tu ide klasa
#ifndef BMI_H
#define BMI_H
class BMI
{
public:
//Default Constructor
BMI();
//Overload Constructor
BMI(string, int, double);
//Destructor
~BMI();
// Accessor functions
string getName() const;
// // // returns name of patient
int getHeight() const;
// // // returns height of patient
double getWeight() const;
// // // returns weight of patient

private:
// member variables
string newName;
int newHeight;
double newWeight;
};
#endif

BMI.cpp:

//Function definitions
#include "BMI.h"
// to access function inside a class
BMI::BMI()
{
newHeight = 0;
newWeight = 0.0;
}
BMI::BMI(string name, int height, double weight)
{
newName = name;
newHeight = height;
newWeight = weight;
}
BMI::~BMI()
{
}
string BMI::getName() const
{
return newName;
}
int BMI::getHeight() const
{
return newHeight;
}
int BMI::getWeight() const
{
return newWeight;
}

编辑:好的,谢谢大家,我解决了部分问题。然而,你让我对编辑有点困惑,所以我会重新做一遍。

原来的代码似乎不起作用,我觉得应该这样做。无论如何,问题中编辑的代码也不起作用。

所以,我会再试一次。但是谢谢你,现在我知道如何编译了。:)

第2版:现在一切正常,非常感谢。

您需要将main.cpp编译为main.o,将BMI.cpp编译为BMI.o.

g++ -c Main.cpp
g++ -c BMI.cpp

然后,您需要将两个对象文件链接到一个可执行文件中(并链接到标准C++库)

g++ -o myprog Main.o BMI.o -lstdc++

使用运行示例

./myprog

似乎有更多的错误,我没有时间修复,请继续。:-)

[marc@quadfork ~/test]$./myprog
Enter your name: foo
Enter your height (cm): 23
Enter your weight (kg): 2
Patient name:
Height: 0
Weight: 0

您的函数在BMI.cpp中返回注释试试这个。

string BMI::getName() const
{
return newName;
}
int BMI::getHeight() const
{
return newHeight;
}
double BMI::getWeight() const
{
return newWeight;
}