对 Class::Class/Function 的未定义引用(OOP 中的初学者)

Undefined reference to Class::Class/Function (Beginner in OOP)

本文关键字:Class OOP 初学者 未定义 Function 引用      更新时间:2023-10-16

我有这个烦人的错误; 对 Shape::Shape(...(, Shape::getName(...(, Shape::getAge(...( 的未定义引用

我的主要.cpp是这个

#include <iostream>
#include <string>
#include "Bit.h"
using namespace std;
int main()
{
    //simple assignment
    string name;
    int age;
    cout<<"enter name: ";
    cin>>name;
    cout<<"enter age: ";
    cin>>age;
    Shape sh(name,age); //class declaration (i think here is the problem)
    cout<<endl<<"name: "<<sh.getName();
    cout<<endl<<"age: "<<sh.getAge();


    return 0;
}

这是 Bit.h 标头

#include <iostream>
#include <string>
using namespace std;
#ifndef BIT_H
#define BIT_H
 //creating class
class Shape{
    string newName;
    int newAge;
public:
    //Default Constructor
    Shape();
    //Overload Constructor
    Shape(string n,int a);
    //Destructor
    ~Shape();
    //Accessor Functions
    string getName();
    int getAge();
};

最后,这是位.cpp

#include "Bit.h"
//constructors and destructor
Shape::Shape(){
    newName="";
    newAge=0;
}
Shape::Shape(string n, int a){
    newName=name;
    newAge=age;
}
Shape::~Shape(){
}
string Shape::getName(){
    return newName;
}
//getters
int Shape::getAge(){
    return newAge;
}

我知道,这可能是一个非常简单的问题/错误,但我已经挣扎了大约 2 个小时。 我想错误在声明 od "sh" 对象中,即使我像这样声明它 "Shape sh((;" 或 "Shape sh;",仍然存在错误。 谢谢

GNU GCC 编译器 编辑2.使用代码块(很抱歉忘记了所有这些(

你可能不是在编译Bit.cpp,而只是在编译Main.cpp

考虑到Bit.hBit.cppMain.cpp在同一个文件夹中,你应该如何编译它:

g++ *.cpp

它仍然无法编译,因为在默认构造函数中,您正在尝试初始化name,并且age两者都不存在。

你可能的意思是newAgenewName

在另一个构造函数中,nameage也不存在,你可能的意思是na