在结构中定义构造函数

defining constructor in a struct

本文关键字:构造函数 定义 结构      更新时间:2023-10-16

尝试查看结构和构造函数如何在标题,实现和主文件中工作。使用构造函数和默认构造函数。我在mains.cpp中遇到了"不确定的'numbers :: numbers()'

的cpp。

在test.h中我有:

#ifndef H_TEST
#define H_TEST
struct numbers{
   int a;
   int b;
numbers();
numbers(int x, int y);
};
#endif

数字。cppi有:

#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;
 }

看来您是通过在构造函数上放入功能主体(尽管空功能主体)来声明标题文件中的内联构造函数。

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

尝试删除标题中的空功能体。

问题是您默认构建了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;
}

我认为您打算重新分配数字:

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;
}

旁注:您通常应避免非符合全局变量。另外,在可能的情况下,在同一行中初始化变量,以避免两次分配数据成员(对于这样的非常小的对象并不重要)。

编辑:我没有注意到量子力学指出的问题。您必须修复两个错误才能按照您的期望工作。