【问题标题】:Undefined reference to Class::Class/Function (Beginner in OOP)对 Class::Class/Function 的未定义引用(OOP 中的初学者)
【发布时间】:2018-04-30 12:57:02
【问题描述】:

我有这个烦人的错误; 未定义对 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 个小时。 我想错误是在声明 od "sh" 对象中,即使我声明它像这样 "Shape sh();"或“Shape sh;”,仍然有错误。 谢谢

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

【问题讨论】:

  • 你如何编译这个?
  • 对不起,我没有在上面添加这个。 GNU GCC 编译器和编译目标是 main.cpp
  • 你需要编译和链接每个cpp文件,而不仅仅是main.cpp
  • 文件中有大量错别字或错误。 (看起来有些已经修复了。)一旦我修复了这些,它就为我正确编译和运行了。

标签: c++ function class object undefined


【解决方案1】:

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

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

g++ *.cpp

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

您可能是指newAgenewName

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

【讨论】:

  • 打错字了,确实还是出现同样的错误
  • 你能告诉我们你当时使用的确切编译行吗?因为它对我有用。
  • 你是这个意思吗? ||=== 构建:在 12345 中调试(编译器:GNU GCC 编译器)===| obj\Debug\main.o||在函数main':| C:main.cpp|16|undefined reference to Shape::Shape(std::__cxx11::basic_string, std::allocator>, int)'| C:main.cpp|18|未定义引用Shape::getName[abi:cxx11]()'| C:\main.cpp|19|undefined reference to Shape::getAge()'| C:\main.cpp|16|未定义引用Shape::~Shape()'| C:\main.cpp|16|undefined reference to Shape::~Shape()'|
  • 我猜是不是打错了,这里打字还是有点问题
  • 我的意思是我告诉你尝试的那个:g++ *.cpp -I./。你在使用 Visual Studio 吗?还是在终端中编译?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
  • 2013-11-08
  • 2012-09-16
  • 2013-03-20
相关资源
最近更新 更多