0


在下面的例子中,

class Car
{
        private:
                int sides;

        public:
                Car()
                {
                        cout<<"\ndefault called constructor";
                }
                Car(int nsides)
                {
                        cout<<"\ncalled constructor";
                        sides=nsides;
                }

};

class Auto
{
        private:
                Car ch;
        public:
        Auto(int a) : Car(a)
        {

                //Car test(5);
        }
};

int main()
{
        Auto at(5);
        return 0;

}

参考以下链接后:-

在通过构造函数传递变量的对象中创建对象

http://www.cplusplus.com/forum/beginner/9746/

我尝试编写相同的代码并执行它。不幸的是,我收到以下编译器错误:-

check.cpp: In constructor ‘Auto::Auto(int)’:
check.cpp:44: error: type ‘Car’ is not a direct base of ‘Auto’

如果给定链接中提到的解决方案是正确的,那么我的代码有什么问题?我的下一个查询是……如果尝试在不使用初始化列表的情况下对其进行初始化,为什么只有参数化的 constructor() 会抛出编译器。
这将引发编译器错误:-

class Auto
{
        private:
                Car ch(5);
        public:
        Auto(int a)
        {

        }
};

但这不是:-

class Auto
{
        private:
                Car ch;
        public:
        Auto(int a)
        {

        }
};

请帮助我理解这种行为。
提前致谢。

4

1 回答 1

3

In your example you are specifying by your constructor Auto(int a) : Car(a) that Auto is derived from Car, and that's what the compiler complains about.

To initialize your Car object (inside of Auto), do this Auto(int a) : ch(a). You put the type instead of the member's name.

About your second question, in-class member initialization is a new feature brought by C++11. You may use it by adding the parameter -std=c++11 to your compiler (GCC or Clang, msvc doesn't support it). See this question. In your case you can use it as chris pointed out :

class Auto {
// ...
Car ch{5};
int someVal = 5;
// ...
};
于 2013-06-21T18:43:39.847 回答