![](/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.