为什么C++程序会出现错误?

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();
}

标题和解释都不太好。下次请至少在标题中说明您的问题。 - Zoltán Schmidt
5个回答

5
当编译器告诉你某个东西不可访问时,它指的是公共、保护和私有访问控制。
默认情况下,类的所有成员都是私有的,因此无法从main(),包括构造函数和方法中访问它们。
要将构造函数设置为公共,请在类中添加一个public:部分,并在其中放置构造函数和方法。
class s_interest
{
    int p,t;
    float r;
public: // <<== Add this
    s_interest(int a, int b, float c)
    {
        ...
    }
    void method()
    {
        ...
    }
};

2

class的默认成员访问级别是private(而struct的默认级别是public)。您需要将构造函数和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++ 头文件。如果您使用符合标准的 C++ 实现,则需要包含 <iostream>


为什么每个人都说要使用 iostream 而不是 iostream.h?我同意 iostream.h 不是标准头文件,但是除了这一点,还需要指出编译器的更改。如果 OP 使用像 Turbo C++ 这样的几十年前的编译器,并且只是更改此头文件,那么将会抛出编译器错误。 - P0W
@P0W 在这里我们正在讨论标准 C++。如果一个问题涉及到前标准的编译器,那么应该由提问者指出这个要求。无论如何,我已经明确了我的上一句话。 - juanchopanza

1

大约在您回答这个问题的4天后,HIC++ V4.0已上传到http://www.codingstandard.com/section/index/。规则已完全重写,主要是为了涵盖自2011年以来的C ++语言特性。恰巧,类成员可访问性顺序不再是一个规则。 - Richard Corden

0
问题出在访问说明符上。默认情况下,类的方法和数据成员是私有的。将您的数据成员设置为私有的,将方法设置为公有的,这样您就可以使用公共方法设置私有数据成员的值。
class{
private:
int a;
int b;
int c;
public:

void method();
void print_sum();

};

0
你的类中所有的变量和函数都是私有的。当没有使用 private:protected:public: 修饰符指定访问权限时,这是默认设置。我建议你好好阅读一下教程——谷歌 C++ 类。
此外,应该使用 int main() 而不是 void main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接