在结构中定义构造函数
defining constructor in a struct
尝试查看结构和构造函数如何在标题,实现和主文件中工作。使用构造函数和默认构造函数。我在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;
}
旁注:您通常应避免非符合全局变量。另外,在可能的情况下,在同一行中初始化变量,以避免两次分配数据成员(对于这样的非常小的对象并不重要)。
编辑:我没有注意到量子力学指出的问题。您必须修复两个错误才能按照您的期望工作。
相关文章:
- 具有enable_if外部类原型的模板类构造函数定义
- 构造函数定义中类声明中的模板值
- C++中的继承和构造函数定义
- 如何使用模板化构造函数定义演绎指南?
- 构造函数定义C
- 不正确的成员构造函数定义
- 具有虚拟多重继承的构造函数定义
- C++谷歌测试在哪里放置测试夹具构造函数定义
- 模板类定义中的模板构造函数定义
- C++下面给出的代码中的构造函数定义差异
- 带继承的构造函数定义
- 无法访问构造函数定义之外的变量
- 调用构造函数定义中的函数后收到Segmentation Fault 11错误
- 将具有默认值的构造函数定义为组合对象的私有字段
- 防止重新定义构造函数定义的方法
- 继承构造函数-定义可移植的固定大小类型(C++)
- 在类的私有部分为复制构造函数定义原型如何防止类的复制
- 如何指定继承类的构造函数定义
- 了解默认移动构造函数定义
- 理解构造函数定义块的语法变化