在C ++类中使用非默认构造函数构造对象 [英] Construction of object with non-default constructor inside C++ class

查看:230
本文介绍了在C ++类中使用非默认构造函数构造对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Iam新到C ++和下面提到的是问题的总结。 Bar的构造函数需要显式调用foo的构造函数,foo的构造函数的参数必须是baz的对象,它有一个默认的构造函数。 Iam不允许使用new运算符(动态分配)来实现这一点。我试过下面的代码,但C ++编译器给我编译错误(下面列出)。有人可以请解释我在这段代码出了什么问题吗?任何帮助都非常感激。

  // Constructor.cpp 
#include< iostream>
using namespace std; // two of two,yay!

class baz {
public:
baz(){};
};

class Foo {
public:
Foo(baz y){}
};

class Bar {
public:
Foo x;
baz y;
Bar():Foo(y){};
};

int main(){
Bar b;
}

语法编译时出错。
--------------------------
constructor.cpp:在构造函数`Bar :: Bar()':
constructor.cpp:19:error:type`Foo'不是`Bar'的直接基础
constructor.cpp:19:error:没有匹配函数调用`Foo :: Foo
constructor.cpp:9:注意:候选者是:Foo :: Foo(const Foo&)
constructor.cpp:11:note:Foo :: Foo(baz)


解决方案

 }; 

你在这里干什么? Foo 不是 Bar 的成员。这是一种类型。 x Foo 类型的成员。



即使你写 x(y),初始化的顺序也有问题。 x 取决于 y ,因此 y x 之前初始化。因此,在 x 之前声明 y ,以确保正确的初始化!



我会建议这个变化:

  class Bar 
{
public:
baz y;
Foo x; //注意:在y之后声明x,因为x取决于y!
Bar():x(y){}
};


Iam new to C++ and below mentioned is the summary of the problem. Bar's constructor needs to explicitly call foo's constructor and the argument to foo's constructor has to be an object to baz, which has a default constructor. Iam not allowed to use new operator(dynamic allocation) to achieve this. I tried the below code, but C++ compiler gives me compilation errors (listed below). Can somebody please explain me what's going wrong in this code? Any help is really appreciated.

//Constructor.cpp
#include <iostream>
using namespace std;    // two of two, yay!

class baz {
public:
baz() { };
};

class Foo {
public:
Foo(baz y) { }
};

class Bar  {
public:
Foo x;
baz y;
Bar() : Foo(y) { };
};

int main() {
Bar b;
}

Syntax Error on compiling.
--------------------------
constructor.cpp: In constructor `Bar::Bar()':
constructor.cpp:19: error: type `Foo' is not a direct base of `Bar' 
constructor.cpp:19: error: no matching function for call to `Foo::Foo()'
constructor.cpp:9: note: candidates are: Foo::Foo(const Foo&)
constructor.cpp:11: note:                 Foo::Foo(baz)

解决方案

Bar() : Foo(y) { };

What are you doing here? Foo is not a member of Bar. It's a type. x is a member of type Foo.

But even if you write x(y), there is a problem in the order of initialization. As x is depending on y, so y must be initialized before x. So declare y before x to ensure the correct initialization!

I would suggest this change:

class Bar  
{
   public:
      baz y;
      Foo x; //NOTE : x declared after y, as x is depending on y!
      Bar() : x(y) {}
};

这篇关于在C ++类中使用非默认构造函数构造对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆