简体   繁体   English

如何在另一个类中调用自定义构造函数

[英]How to call a custom constructor inside another class

If I have 2 classes, one with a custom constructor, and the other with an instance of the first class. 如果我有2个类,一个带有自定义构造函数,另一个带有第一个类的实例。 How do I create that instance with the custom constructor. 如何使用自定义构造函数创建该实例。

For example: 例如:

ah

class A
{
public:
    A(std::string input);
};

bh h

Class B
{
public:
    A a("Greetings");
};

This wouldn't work properly, it gives the error "expected a type specifier" on the string itself, and whenever I use a member of class A in class B, it says "expression must have a class type" 这将无法正常工作,它会在字符串本身上产生错误“ expected a type specifier”,并且每当我在B类中使用A类的成员时,都会说“表达式必须具有类类型”

I'm assuming this means I'd need to make it 我假设这意味着我需要做到

A a(std::string words);

But I'm not sure where or how I would define what the string should be. 但是我不确定在哪里或如何定义字符串应该是什么。

Use the constructor's initialization list : 使用构造函数的初始化列表

class A
{
public:
    A (std::string input);
};

class B
{
    A a;
public:
    B (std::string s) : a (s) {}; //This calls the constructor of A on 'a'
};

Also, in C++11 you can use the uniform initializer syntax : 另外,在C ++ 11中,您可以使用统一的初始化程序语法

class B
{
    A a {"Greetings"}.
    ...
};

But with this, you can only call the constructor with a compile-time constant. 但是,有了这个,您只能使用编译时常量来调用构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM