初始化堆分配的对象时出错

时间:2011-11-12 06:58:03

标签: c++ object initialization

我正在尝试按如下方式初始化堆分配的对象:

class Ball {
  int radius;
  string colour;
};

int main(){
    Ball *b = new Ball { radius = 5, colour = "red" };
}

想知道为什么这会给我一个错误? 感谢

5 个答案:

答案 0 :(得分:3)

这不是你用C ++初始化对象的方式。

这是一种方法:

class Ball {
    int radius;
    string colour;

public:

    //  Define a Constructor
    Ball(int _radius, const string &_colour)
        : radius(_radius)
        , colour(_colour)
    {
    }
};

int main(){
    Ball *b = new Ball(5, "red");

    delete b;  //  Don't forget to free it.
}

答案 1 :(得分:0)

使用()代替{}。你正在调用一个构造函数,它只是一个实例化对象的特殊函数。

因此,语法如下所示:

Ball* b = new Ball(5, "red");

另请注意,构造函数中的参数顺序(“red”之前的5)指示哪个变量分配给哪个值。因此,您不要将变量名称放在构造函数调用中。

答案 2 :(得分:0)

很多问题!

试试这个:

class Ball {
public:
  Ball(int r, const string &s)
  {
    radius = r;
    colour = s;
  }
  int radius;
  string colour;
};

int main(){
    Ball *b = new Ball(5, "red");
    // ....
    // delete b;  <-- dont forget
}

答案 3 :(得分:0)

创建对象时,使用( ... )代替{ ... },无需编写变量名称。只需传递要分配的值。

Ball *b = new Ball { radius = 5, colour = "red" };` // Wrong

将其更改为

Ball *b = new Ball ( 5, "red" );

并且,不要忘记在a constructor课程的Ball课程中声明public

Ball(int, std::string);

答案 4 :(得分:0)

这适用于C ++ 11:

struct Ball {
  int radius;
  std::string colour;
};

int main() {
  Ball* b = new Ball({ 5, "red" });
}
相关问题