【问题标题】:initialise string array or 2d char array in derived class in c++在 C++ 派生类中初始化字符串数组或二维字符数组
【发布时间】:2014-11-02 05:32:01
【问题描述】:

这是一个sn-p:

class student
   {
    protected:
     string name, subject[6];
      ....
    };
class ugstudent : public student
{
   ...
};
class ugfirst_yr : public ugstudent
{
subject[6] = {"phy", "chem", "math", "electrical", "civil", "comp"};  //error*
 public:
  ...
};

*我在上述初始化中得到的错误:“这个声明没有存储类或类型说明符”, 对于数组中的内容:“const char *”类型的值不能用于初始化“int”类型的实体

我想要的是字符串数组 subject[] 是通用的,但是从类 ugstudent 派生的每个类中数组的内容应该不同。我应该改变什么?

【问题讨论】:

  • 你不能像这样初始化数据成员,即使在 C++11 中也是如此。顺便问一下,你用的是什么编译器?隐含的 int 错误信息看起来很奇怪。
  • 如果学生类型之间的行为没有变化,我不会在这里使用继承。而是将主题作为学生类的构造函数参数传递。
  • @NeilKirk 此处需要继承。但在这个 sn-p 中没有看到。并且 vector 没有任何区别:(仍然是相同的错误!
  • 你可以使用 C++11 吗?你的编译器是什么。
  • 但是我在各个派生类的构造函数中初始化了主题,所以它可以工作:) 我使用 Visual Studio。

标签: c++ inheritance arrays


【解决方案1】:

试试这样的

class student
{
public:
    vector<string> subject;

    student()
    : subject{ "a", "b", "c" }
    {
    }
};

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2014-05-14
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多