【问题标题】:How to fix the Error in static member that is private?如何修复私有静态成员中的错误?
【发布时间】:2019-02-13 09:05:15
【问题描述】:

为什么 i 被称为私有?因为 i 是静态成员,那么它一定不是第 19 行的错误

#include<iostream>
using namespace std;
class myClass{
    static int i;
public:
    void seti(int a)
    {
        i=a;
    }
    int geti()
    {
        return i;
    }
};
int myClass::i;
int main()
{
    myClass ob1,ob2;
    cout<<myClass::i<<endl;
    ob1.seti(200);
    cout<<ob1.geti()<<endl;
    cout<<ob2.geti()<<endl;
}

【问题讨论】:

  • 可以添加语言名称吗?
  • 公开i 还是不要尝试直接访问?
  • @IvoMerchiers C++

标签: c++ variables static declaration member


【解决方案1】:

这里的问题是class 的成员属性默认为private。这意味着 i 是私有的,您无法从课堂外访问它。

一种解决方案是将i 声明为公共成员。

class myClass{
public:
    static int i;
    void seti(int a)
    {
        i=a;
    }
    int geti()
    {
        return i;
    }
};

PS : struct 的成员默认是公开的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-02
    • 2020-03-22
    • 2015-09-26
    • 1970-01-01
    • 2015-05-17
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多