c++ - 如何全局创建对象并使用该对象访问全局范围内的公共成员函数?
问题描述
我正在尝试全局创建一个对象并尝试在构造函数的帮助下访问公共成员函数。但它显示错误,有人可以帮助我吗?
在这里,我创建了一个名为 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 ^
解决方案
这是正确的形式
#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;
}
推荐阅读
- linux - 证明顶部 100% 的核心实际上是自旋锁定的最佳性能指标
- java - org.apache.oozie.action.hadoop.JavaMainException:java.io.FileNotFoundException
- visual-studio-code - 在 Visual Studio Code 中格式化时保留换行符
- corda - 迁移到 Oracle 11g 时出错“请检查正确的 JDBC 驱动程序...”
- alexa - Amazons Alexa:语音历史记录中不显示请求
- java - 使用范围而非容器的 Java JTwig For 循环
- android - 删除被杀死的前台服务的通知图标(Android)
- angularjs - PWA 添加到主屏幕后会丢失其参数和查询参数
- liquibase - Liquibase 中的上下文,在除一个之外的任何上下文中运行
- git - 在 Git 中隐藏/锁定提交历史