[英]defining constructor in a struct
試圖查看結構和構造函數在標頭,實現和主文件中的工作方式。 使用構造函數和默認構造函數。 我在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;
}
好像您是通過為構造函數放入函數主體(盡管函數主體為空)在頭文件中聲明內聯構造函數的。
我希望在包含標頭的文件中,當編譯器看到內聯定義時,它將使用那些內聯定義,因此永遠不會生成與.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;
}
我認為您打算重新分配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;
}
注意事項:通常應避免使用非常量全局變量。 另外,在可能的情況下,請在聲明它們的同一行中初始化變量,以避免兩次分配數據成員(對於像這樣的很小的對象來說,這並不重要)。
編輯:我沒有注意到QuantumMechanic指出的問題。 您必須修復這兩個錯誤,程序才能按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.