【问题标题】:Array of class with a const member in C++ [duplicate]C ++中具有const成员的类数组[重复]
【发布时间】:2013-07-11 12:12:56
【问题描述】:

我想初始化一个类数组,其中包含一个必须在构造时初始化的 const 成员。

#include <iostream>
class A
{
    private:
        const int var_;

    public:
        A(const int var) : var_(var){};

        int getVar(){return var_;}
};

class B
{
    private:
        A tab[2];

    public:
        B() : tab{2,5} {}; // The trick should be here, I think !

        int getA(int index) { return tab[index].getVar();}
};

int main(void)
{

    B b; // constraint : Dynamic allocation not allowed
    std::cout << b.getA(0) << std::endl;

    return 0;
}

此代码无法编译,因为 B 类的构造函数不正确。 谢谢你的帮助, 尼古拉斯

【问题讨论】:

  • 问题到底是什么?
  • 编译不出来是什么意思? (错误?)
  • 编译只是说“不正确”,还是给出了一些细节?如果提供详细信息,请告诉我们。
  • 这对我来说编译得很好。你用的是哪个编译器?
  • 法语翻译不好,我的意思是数组而不是表格。

标签: c++


【解决方案1】:

命令

g++ -std=c++11 1.cpp

编译上面的代码就好了。运行 1.exe 在控制台中打印 2

P.S:g++.EXE (GCC) 4.9.0 20130616(实验性)

【讨论】:

  • 我不能用 c++11 但谢谢。
  • 你的代码使用了 C++11 特性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
相关资源
最近更新 更多