【发布时间】:2021-07-10 19:09:00
【问题描述】:
我正在使用一个代码,其中我将一个常量变量传递给这样的模板结构
#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,由main函数赋值),而不传递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;
^~~
那么我如何在函数“show()”中读取“T age”的值而不将 struct 变量作为参数从“int main()”传递?
非常需要更正代码和适当的解释。
【问题讨论】:
-
您可以将
person声明为全局变量...但我强烈反对使用全局变量。或者你可以定义show(),在main()里面,作为一个lambda函数,捕获person;比如auto show = [&]{ std::cout << person.age; }; -
我的建议是通过一个人显示使用参考。或者让 show 成为 Data 的成员
-
@Max66 真的很抱歉兄弟,在我的代码中,我不能使用 lambda,我只想从用户定义的函数 show() 中读取变量。
-
@drescherjm 请提供代码示例
-
在
T age;之后和下一个};之前放void show() { cout << age; }