如何将构造函数由一个参数组成的对象传递给C ++中的函数? [英] How to pass object whose constructor consist of one argument to a function in C++?

查看:253
本文介绍了如何将构造函数由一个参数组成的对象传递给C ++中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个类B,其构造函数接受其他类(类A)的对象作为参数。 A类构造函数也由参数组成。我得到错误,如下所述。这里有什么问题?

 #include< iostream> 
using namespace std;
class A {
int val;
A(int val){
this-> val = val;
}
};
class B {
A a;
B(A& x){
a = x;
}
};
int main(){
A tempa(3);
B tempb(tempa);
}

错误:

  temp.cpp:在构造函数'B :: B(A&)':
temp.cpp:13:9:错误:没有匹配的函数调用' :A()'
temp.cpp:13:9:note:candidate are:
temp.cpp:6:2:note:A :: A(int)
temp.cpp :6:2:note:candidate expects 1 argument,0 provided
temp.cpp:3:7:note:A :: A(const A&)
temp.cpp:3:7:note :candidate expects 1 argument,0 provided


解决方案

明确初始化一个数据成员是在构造函数初始化列表中。一旦你在构造函数的主体中,成员已经被初始化,你所能做的就是修改它。在你的情况下,由于你不这样做,数据成员会隐式地默认默认构造,但 A 没有默认构造函数。 / p>

您需要在构造函数初始化列表中使用适当的构造函数:

  B(A& x):a(x)
{
}


I have defined a class B, whose constructor accept object of other class(class A) as parameter. Class A constructor also consist of parameter. I am getting error as described below. What is the problem here?

#include<iostream>
using namespace std;
class A{
    int val;
    A(int val){
        this->val=val;
    }
};
class B{
    A a;
    B(A& x){
        a=x;
    }
};
int main(){
    A tempa(3);
    B tempb(tempa);
}

Error:

temp.cpp: In constructor ‘B::B(A&)’:
temp.cpp:13:9: error: no matching function for call to ‘A::A()’
temp.cpp:13:9: note: candidates are:
temp.cpp:6:2: note: A::A(int)
temp.cpp:6:2: note:   candidate expects 1 argument, 0 provided
temp.cpp:3:7: note: A::A(const A&)
temp.cpp:3:7: note:   candidate expects 1 argument, 0 provided

解决方案

The only way to explicitly initialize a data member is in the constructor initialization list. Once you are in the body of the constructor, the member has been initialized, and all you can do is modify it. In your case, since you are not doing this, the data member would bet implicitly default constructed, but A does not have a default constructor.

You need to use the appropriate constructor in the constructor initialization list:

B(A& x) : a(x)
{
}

这篇关于如何将构造函数由一个参数组成的对象传递给C ++中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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