首页 文章

cpp-如何用const int decalare和实现函数[关闭]

提问于
浏览
-3

我尝试以下列方式实施基础 class 的学生:

class Student
{
    public:
        Student(std::string name_ , int const id_);
        virtual ~Student();
        void addGrade(int const grade2add);
        void print();

    private:
        std::string name;
        int const id;
        std::vector<int> grades;
        int cost maxGrade;
};

构造函数:

Student::Student(std::string name_, int const id_): name(name_), id(id_)
{
    if (name.size()>=20)
    {
        cout<<"Name should be less than 20 chars"<<endl;
    }
    if (id.size()!=5)
    {
         cout<<"Id should be 5 nums"<<endl;
    }
}

主要:使用命名空间std;

int main()
{
    cout << "Hello School!" << endl;
    Student sarit_student("Sarit Rotshild",12345);
    return 0;
}

*包括所有相关的库和文件 . 我收到以下错误:错误:未初始化的成员'Student :: maxGrade'与'const'类型'const int'[-fpermissive]

1 回答

  • 0

    要回答您的问题,您可以使用const参数实现一个函数

    #include <iostream>
    
    
    class A {
    public:
    
        A(const int a_foo) 
        : m_foo(a_foo)
        {}
    
        void bar(const int a_baz) {
            std::cout << "member variable : " << m_foo << std::endl;
            std::cout << "const parameter/argument : " << a_baz << std::endl;
            //m_foo = a_baz;  //won't work
        }
    
    private :
        const int m_foo;
    };
    
    int main() {
    
        A a(10);
        a.bar(20);
    
        return 0;
    }
    

    此外,正如NathanOliver指出的那样,您向我们展示的错误并没有在任何地方看到任何maxGrade成员变量 . 错误似乎是你的maxGrade成员还没有被初始化(在将每个变量包含到操作中之前完成 should ) . 在旁注中,您可以编写 int const foo = 10; ,但是更为标准化的方式来声明您的变量将是 const int foo = 10; ,如here所述 . 你只需要知道它们代表什么,当你将它与指针混合时可能会让你感到困惑,例如你可以做到 const int const* foo; .

    此外,我有一些困难,即使您显示的错误不存在,我相信您显示的代码将编译,因为您正在调用 id.size() ,而 id 是一个int ...

相关问题