首页 > 解决方案 > 如何全局创建对象并使用该对象访问全局范围内的公共成员函数?

问题描述

我正在尝试全局创建一个对象并尝试在构造函数的帮助下访问公共成员函数。但它显示错误,有人可以帮助我吗?

在这里,我创建了一个名为 base 的类,并尝试通过创建构造函数在全局范围内访问该类的公共成员函数。

    #include <iostream>
    using namespace std;


    class base
    {
        void privatef()
        {
            cout<<"This is function from private scope\n";
        }
        public:
        void publicf()
        {
            cout<<"This is function from public scope\n";
        }

        protected:
        void protectedf()
        {
            cout<<"This is function from protected scope\n";
        }
    };

    base()
    {
            publicf();
            //privatef();
            //protectedf();
    }

    base d;

    class derived :public base
    {
        public:
        derived()
        {
            //privatef();
            publicf();
            protectedf();
        }
    };


    int main()
     {
        derived d1 ;
        return 0;
     }

错误:错误:')' 标记 base() 之前的预期不合格 ID ^

标签: c++

解决方案


这是正确的形式

#include "stdafx.h"
#include <iostream>
using namespace std;


class base
{

    void privatef()
    {
        cout << "This is function from private scope\n";
    }
public:
    //Declare it at least first & then define it outside
    base();
    void publicf()
    {
        cout << "This is function from public scope\n";
    }

protected:
    void protectedf()
    {
        cout << "This is function from protected scope\n";
    }
};

base::base()
{
    publicf();
    //privatef();
    //protectedf();

}

base d;

class derived :public base
{
public:
    derived(){

        //privatef();
        publicf();
        protectedf();
    }
};


int main()
{
    derived d1;
    return 0;
}

推荐阅读