在类构造函数

时间:2016-04-05 12:39:30

标签: c++ oop initializer-list

我正在尝试完成一个非常简单的事情:当创建类的实例时,即在调用构造函数时,应该初始化类的受保护const成员(获取值)。像这样:

MyClass.hpp:
class MyClass {
public:
   //some methods

MyClass(){}    //Constructor
protected:
const int Variable;
};

MyClass.cpp: 

//some method definitions
MyClass::MyClass(int newVariable): Variable(newVariable) {} //constructor

我已尝试过static个关键字和其他内容,每个都给出了自己或多或少有启发性的编译错误。在示例中,“隐式删除了”复制赋值运算符“。

这一切都令人沮丧,因为一切正常,直到我开始保护会员。

作为旁注:如果const成员一旦定义就无法修改,是否仍需要保护和编写getter / setter方法?它确实没有加快发展......

编辑:相关代码:

#ifndef Servo_hpp
#define Servo_hpp
#pragma once

class Servo{
  friend class Grid;
 public: 
    Servo(int newID, int newRow, int newCol);
    //Some other methods

const int row;

const int column;

const int number;

double currentAngle;

double nextAngle;

double currentSpeed;

const int ID;   //TODO: Change to new grid
};

#endif /* Servo_hpp */

Servo::Servo (int newID, int newRow, int newCol): ID(newID), column(newCol), row(newRow), currentAngle(0), currentSpeed(0), number(0){}

最后一部分是在.cpp文件中

修改2

当我尝试创建MyClass的矢量数组时会出现问题:

 std::vector<MyClass> MyClassArray;
     for (int Variable = 0; Variable < 5; Variable++) {
         MyClassArray.push_back(*new MyClass(Variable));
     }
 }  

当我将此代码与上面的类定义放在一起时,这符合g ++,但是XCode给出错误“Object of Type'MyClass'无法分配,因为它的副本赋值运算符被隐式删除”。我可以理解这个问题:一个人不能指定一个const成员,但是我不会在任何地方复制一个MyClass,是吗?

1 个答案:

答案 0 :(得分:1)

  

在示例中,“隐式删除了”复制赋值运算符“。

这很有道理。赋值是一个变异操作,应该突变const对象(您的数据成员)。您已将您的课程设计为不可分配。

请注意protected与此无关。

注意2:如果您希望能够默认构造类,则需要在默认构造函数中初始化其数据成员:

MyClass(): Variable(42) {}
相关问题