3

我想我已经在这个程序中正确编码了所有内容,但仍然出现错误。si它说它不可访问的对象。

#include<conio.h>
#include<iostream.h>

class s_interest
{
    int p,t;
    float r;
    s_interest(int a, int b, float c)
    {
        p=a;
        r=b;
        t=c;
    }

    void method()
    {
        int result=(float)(p*t*r)/100;
        cout<<"Simple interest:"<<result;
    }
};

void main()
{
    int pr,ti;
    float ra;
    cout<<"\n Enter the principle, rate of interest and time to calculate Simple Interest:";
    cin>>pr>>ti>>ra;
    s_interest si(pr,ti,ra);
    si.method();
}
4

5 回答 5

5

当编译器告诉您某些东西不可访问时,它是在谈论public:vs. protected:vs.private:访问控制。默认情况下,类的所有成员都是private:,因此您不能从 访问它们中的任何一个main(),包括构造函数和方法。

要制作构造函数public,请在您的类中添加一个public:部分,并将构造函数和方法放在那里:

class s_interest
{
    int p,t;
    float r;
public: // <<== Add this
    s_interest(int a, int b, float c)
    {
        ...
    }
    void method()
    {
        ...
    }
};
于 2013-09-29T10:59:25.723 回答
2

a 的默认成员访问权限classprivate(而默认成员访问权限structpublic)。您需要制作构造函数和method() public

class s_interest
{
  int p,t;  // private
  float r;  // also private


public: // everything that follows has public access

  s_interest(int a, int b, float c) { .... }
  void method() { ....}
};

另请注意,这void main()不是标准的 C++。返回类型需要是int,所以你需要

int main()
{
  ...
}

最后,iostream.h不是标准的 C++ 头文件。<iostream>如果您使用的是符合标准的 C++ 实现,则需要包括在内。

于 2013-09-29T10:59:08.287 回答
1

遵循高完整性 C++ 编码标准指南,始终首先声明public,然后是 protected 和 private 成员。参见hicpp-manual-version-3-3.pdf 的规则 3.1.1

于 2013-09-29T12:37:47.170 回答
0

您班级中的所有变量和函数都是私有的。private:当没有使用,protected:和说明符指定访问权限时,这是默认设置public:。我建议你好好阅读一个教程——谷歌 C++ 类。

它也是int main()并且永远不会void main()

于 2013-09-29T11:00:52.403 回答
0

问题是由于访问说明符。默认情况下,类方法和数据成员是私有的。将您的数据成员设为私有,将方法设为公开。因此您可以使用公共方法设置私有数据成员的值。

class{
private:
int a;
int b;
int c;
public:

void method();
void print_sum();

};
于 2013-09-29T11:33:18.237 回答