How to initialise Constructor of a Nested Class in C++

廉价感情. 提交于 2019-12-23 12:24:45

问题


I am getting problems in initializing the nested class constructor.

Here is my code:

#include <iostream>

using namespace std;

class a
{
public:
class b
{
    public:
    b(char str[45])
        {
        cout<<str;
        }

    }title;
}document;

int main()
{
    document.title("Hello World"); //Error in this line
    return 0;
}

The error I get is:

fun.cpp:21:30: error: no match for call to '(a::b)'

回答1:


You probably want something like:

class a
{
public:
    a():title(b("")) {}
    //....
};

This is because title is already a member of a, however you don't have a default constructor for it. Either write a default constructor or initialize it in the initialization list.




回答2:


You have to either make your data member a pointer, or you can only call the data member's constructor from the initialiser list of the construtor of the class it is a member of (in this case, a)




回答3:


This:

document.title("Hello World");

is not "initializing the nested class"; it's attempting to call operator() on the object.

The nested object is already initialised when you create document. Except that it's not, because you've provided no default constructor.




回答4:


So what do you have here:

class A {
  B title;
}

Without defining constructor for class A (as Luchian Grigore shown) title will be initialized as: B title();

You can work that around by:

A::A():title(B("Hello world"))

// Or by adding non parametric constructor:
class B {
  B(){

  }

  B( const char *str){

  }
}

Object title (in document) is already initialized and you cannot call constructor anymore, but you still may use syntax: document.title(...) by declaring and defining operator() but it won't be constructor anymore:

class B {
  const B& operator()(const char *str){
     cout << str;
     return *this;
  }
}


来源:https://stackoverflow.com/questions/9160267/how-to-initialise-constructor-of-a-nested-class-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!