在结构中定义构造函数

时间:2016-06-18 02:06:53

标签: c++ struct constructor

尝试查看结构和构造函数在头文件,实现文件和主文件中的工作方式。使用构造函数和默认构造函数。我在mains.cpp中得到编译错误"未定义引用' numbers :: numbers()'

在test.h中我有:

#ifndef H_TEST
#define H_TEST

struct numbers{

   int a;
   int b;
numbers();

numbers(int x, int y);

};
#endif

在Numbers.cpp中我有:

#include "test.h"

 numbers::numbers()
  {
     a=0;
     b=0;
  }
  numbers::numbers(int x, int y)
  {
      a=x;
      b=y;
  }

在mains.cpp中我有:

 #include<iostream>
 #include "test.h"
 using namespace std;

 numbers num;//compilation error occurs here
 int main()

{





 return 0;
 }

2 个答案:

答案 0 :(得分:3)

看起来你通过为构造函数添加函数体(尽管是空函数体)来在头文件中声明内联构造函数。

我希望在包含头文件的文件中,当编译器看到内联定义时,它将使用这些,因此永远不会生成符号以与.cpp文件中的定义链接,因此也不会生成.cpp中的定义文件不会被调用。

尝试删除标题中的空函数体。

答案 1 :(得分:3)

问题在于您是默认构建num而不是重新分配它。

numbers num; // Constructs a numbers object with a = 0, b = 0 and stores it in num.
int main()
{
    numbers(3,5); // Constructs a numbers object with a = 3, b = 5.
                  // The object is discarded after the constructor call finishes.

    cout<<num.a; // Prints a from the global variable num.

    return 0;
}

我认为您打算重新分配num:

numbers num; // num is default-constructed to a = 0, b = 0, as before.
int main()
{
    num = numbers(3,5); // num now holds a = 3, b = 5.

    cout<<num.a; // Prints 3, as expected.

    return 0;
}

附注:您通常应避免使用非const全局变量。另外,如果可能的话,在声明它们的同一行中初始化变量,以避免两次分配数据成员(对于像这样的非常小的对象,这并不重要。)

编辑:我没有注意到QuantumMechanic指出的问题。您必须修复这两个错误,以使程序按预期工作。