如何在另一个对象的构造函数中声明和创建对象?

时间:2015-05-08 00:38:09

标签: c++

我正在学习c ++。我想在另一个对象中创建几个对象但是编译器给出错误 - 没有匹配函数来调用'Grass :: Grass()'

这是“world”对象的头文件。在其中我宣布了两个“草”对象: -

#ifndef WORLD_H
#define WORLD_H
#include "Grass.h"

using namespace std;

class World
{
public:
World();

private:
Grass g1;
Grass g2;
};

这是“world”对象的cpp文件。在构造函数中,我尝试制作“草”对象但失败了。

#include "World.h"
#include <iostream>

using namespace std;

World::World()
{
g1(200, 200);
g2(300, 200);
} 

1 个答案:

答案 0 :(得分:3)

你的语法错了。您正在寻找所谓的构造函数初始化列表。尝试(假设你已经获得World::World() : g1(200, 200), g2(300, 200) { // Nothing } 构造函数的签名正确):

function dice1(){
   var randomNumber =  Math.floor(Math.random() * 6) + 1;
   $('#instructions').append(randomNumber);
   return randomNumber;