【问题标题】:Structures inside private私有内部结构
【发布时间】:2014-06-14 18:18:04
【问题描述】:

我不知道如何在类中使用结构。我认为我的第一部分是正确的,但主要没有任何作用。当我尝试运行我的程序时,它说“函数不接受 0 个参数”我应该像这样在 main 中编写所有内容:

P.Read(BOX m);

到目前为止,这是我的代码:

#include <iostream>
#include <string>
using namespace std;
template <class T, int n>
class SIX
{
private:
    struct BOX
    {
        T a[n];
        string name;
    };
public:
    void Read(BOX m)
    {
        cout<<"Enter your name: ";
        cin>>m.name;
        cout<<m.name<<" please enter "<<n<<" data: ";
        for(int i=0;i<n;++i)
            cin>>m.a[i];
    }
    void SortArray(BOX m)
    {
        sort(m.a, m.a+n);
    }
    void Display(BOX m)
    {
        cout<<m.name<<" this is the sorted list of data in your array a: ";
        for(int i=0;i<n;++i)
            cout<<m.a[i]<<'\t';
        cout<<endl;
    }
};
int main()
{
    SIX <int, 6> P; 
    SIX <string, 5> Q;

    P.Read();
    P.SortArray();
    P.Display();
    cout<<endl;

    Q.Read();
    Q.SortArray();
    Q.Display();
    cout<<endl;

    system("pause");
    return 0;
}

【问题讨论】:

    标签: c++ class struct private


    【解决方案1】:

    不,将Read 定义为

    void Read()
    {
        cout<<"Enter your name: ";
        cin>>BOX.name;
        cout<<BOX.name<<" please enter "<<n<<" data: ";
        for(int i=0;i<n;++i)
            cin>>BOX.a[i];
    }
    

    Read 是一个成员函数,它可以访问Box,所以这就是你所要做的。 其他函数也一样,你不需要指定BOX m作为参数,在代码中用()替换它,用BOX替换m

    正如@Barmar 所指出的,您的struct BOX 只是定义了一个类型,您应该定义一个名为BOX 的成员变量。最简单的方法是将BOX 移动到struct 声明的末尾,

    struct
    {
        T a[n];
        string name;
    } BOX;
    

    【讨论】:

    • BOX 不是变量,它是结构类型。
    • 哦,是的,你是对的,但他应该将其设为成员变量。我读得很快,首先想到的是他定义了变量,因为他实际上并没有使用类外的类型。
    • 这是我在使用 [ T= 编译类模板成员函数 'void SIX::SortArray(void)' 时尝试运行它时得到的结果整数,n=6]
    • 您需要在顶部执行 #include 以包含 std::sort() 的代码。
    • 我让它工作了,我忘记添加#include 但是你们建议的更改也有帮助!谢谢
    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多