![](/img/trans.png)
[英]Macro or c++ template to change const variable value in struct or class
[英]How to access a template struct const variable in CPP
我正在使用一個代碼,其中我將一個常量變量傳遞給這樣的模板結構
#include <iostream>
using namespace std;
//Compiler version g++ 6.3.0
template<typename T>
struct Data {
T age;
};
void show();
int main()
{
Data<const int> person{
18
};
cout << person.age;
show();
}
void show(){
}
在代碼中,我想在函數“show()”內部讀取 const 變量“Tage”(Tage 值為 18,由主函數分配),而不將 struct 變量作為參數傳遞。
這是我嘗試過的
#include <iostream>
using namespace std;
//Compiler version g++ 6.3.0
template<typename T>
struct Data {
T age;
};
void show();
int main()
{
Data<const int> person{
18
};
cout << person.age;
show();
}
void show(){
Data<const int> person;
cout << person.age;
}
錯誤信息
source_file.cpp: In function ‘void show()’:
source_file.cpp:32:18: error: use of deleted function ‘Data<const int>::Data()’
Data<const int> person;
^~~~~~
source_file.cpp:10:12: note: ‘Data<const int>::Data()’ is implicitly deleted because the default definition would be ill-formed:
struct Data {
^~~~
source_file.cpp:10:12: error: uninitialized const member in ‘struct Data<const int>’
source_file.cpp:11:8: note: ‘const int Data<const int>::age’ should be initialized
T age;
^~~
那么,如何在不將結構變量作為參數從“int main()”傳遞的情況下讀取 function“show()”中的“T age”值?
非常需要使用代碼進行更正並進行適當的解釋。
您的代碼根本不起作用。 person
變量不會填充到show()
的主體中,因此在 function 中,您只需創建一個不指定值的默認結構。 最后,它崩潰了。
你可以做的是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.