gpt4 book ai didi

c++ - 对 Class::Class/Function 的 undefined reference (OOP 初学者)

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

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

我的Main.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();

};

最后,这是 Bit.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 个小时。我想错误出在“sh”对象的声明中,即使我这样声明它“Shape sh();”或“Shape sh;”,仍然有错误。谢谢

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

最佳答案

您可能没有编译 Bit.cpp,而只是编译 Main.cpp

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

g++ *.cpp

它仍然不会编译,因为在默认构造函数中,您正在尝试初始化 nameage,它们都不存在。

您可能是指 newAgenewName

在另一个Constructor中,nameage也不存在,你可能指的是n,和a?

关于c++ - 对 Class::Class/Function 的 undefined reference (OOP 初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50101057/

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