【问题标题】:Undefined reference to constructor problem构造函数问题的未定义引用
【发布时间】:2021-11-14 17:20:05
【问题描述】:

查看下面给出的代码

#include <iostream>
using namespace std;

class Number
{
    int a;

public:
    Number();

    Number(int num_1) {
        a = num_1;
    }

    void print_number(void) { cout << "Value of a is " << a << endl; }
};

int main()
{
    Number num_1(33), num_3;
    Number num_2(num_1);

    num_2.print_number();
    return 0;
}

在上面的代码中,我在同一个类中有 2 个构造函数,但是在编译它时,给了我错误

ccnd0o9C.o:xx.cpp:(.text+0x30): undefined reference to `Number::Number()'
collect2.exe: error: ld returned 1 exit status  

谁能解决这个问题?我仍然需要 2 个构造函数,但没有用 num_3() 替换 num_3 主函数。

【问题讨论】:

  • 错字:将 Number(void); 更改为 Number(){}

标签: c++ class oop c++11 constructor


【解决方案1】:

在你的类中,你已经声明了默认构造函数,但你还没有定义它。

你可以default it(C++11 起),你会很高兴的:

Number() = default;

否则:

Number() {}

正如@TedLyngmo 喜欢的帖子一样,两者的行为相同,但是根据标准,该类将获得不同的含义。更多阅读: The new syntax "= default" in C++11


@Jarod42 的注释作为旁注:默认构造函数在为成员 a 提供默认值时才有意义。否则它将是未初始化的(不确定的值)和reading them will cause to UB

【讨论】:

  • 这是最好的方法。见reasons
  • 注意= default;{}在这里是有风险的,因为a不会被初始化,所以num_3.print_number();会导致UB。
  • Number(int num_1 = 0) 作为替代方案可能有意义。
【解决方案2】:

使用此代码

#include <iostream>

using namespace std;
class Number
{
    int a;

public:
    Number(){};
    Number(int num_1)
    {
        a = num_1;
    }

    void print_number(void) { cout << "Value of a is " << a << endl; }
};

int main()
{
    Number num_1(33), num_3;

    Number num_2(num_1);
    num_2.print_number();

    return 0;
}

【讨论】:

  • 如果您解释了为什么需要此代码,您的回答会更有用。
  • 不知道 OP 代码有什么问题的人会发现很难发现您所做的更改。答案应该更多地是解释问题和解决方案,而不是提供现成的代码。
  • 注意{}(甚至= default;)在这里是有风险的,因为a不会被初始化,所以num_3.print_number();会导致UB。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多