constint模板似乎在结构中不起作用

我正在使用一个代码,它需要一个结构模板,它应该包含一个像这样的常量 int 变量

#include <iostream>
using namespace std;


template <typename T>
struct person {
  T age;
};



int main()
{
   struct person <const int> man;

   man.age=18;

   cout << man.age;
}

不幸的是,上面的代码不起作用。

当我像这样将实例模板设置为 int 或 char 时,它会起作用

struct person<int> man;

或者

struct person<char> man;

但不是当我这样做

struct person<const int> man;

有没有其他方法可以做我需要做的事情?请用适当的解释指出我的错误。

回答

如果你想T成为一个const int,这意味着ageconst,不能分配给像你这样做

man.age=18;

你需要做的初始化是age当你创建man喜欢

person<const int> man{18};

现在age18也不能改变。另请注意,我删除了struct. 与 C 不同,在 C++ 中,您不需要重复struct来标识类。

  • @SubhaJeetSikdar Please ask a new question instead of editing this one.

以上是constint模板似乎在结构中不起作用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>