【问题标题】:cpp- how to decalare and implement function with const int [closed]cpp-如何用 const int 声明和实现函数 [关闭]
【发布时间】:2016-03-15 14:17:25
【问题描述】:

我尝试通过以下方式实现学生的基本课程:

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

主要内容: 使用命名空间标准;

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

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

【问题讨论】:

  • 您的错误信息与您拥有的代码不匹配。 Student::maxGrade 是什么,这个错误来自源代码中的哪一行?
  • 在您的构造函数中,您是否应该检查id 是否有五位数字?那么这不是这样做的方法(你不能在像int 这样的简单类型上调用“成员函数”)。进行检查也有点晚了,特别是如果您除了打印消息之外什么都不做。
  • 你应该把问题所在的洞码放上去。
  • @NathanOliver- 在构造函数的行中- Student::Student(std::string name_, int const id_): name(name_), id(id_)

标签: c++ constants


【解决方案1】:

要回答你的问题,你可以像这样实现一个带有 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 成员尚未初始化(应该在将每个变量包含到操作中之前对它们进行初始化)。附带说明一下,您可以编写 int const foo = 10;,但更标准化的方式来声明变量将是 const int foo = 10;,如 here 所述。你只需要知道它们代表什么,当你将它与指针混合时可能会造成混淆,例如你可以在哪里做const int const* foo;

此外,我很难相信即使您显示的错误不存在,您向我们展示的代码也会编译,因为您正在调用 id.size()id 是一个 int...

【讨论】:

  • @much_a_chos- 谢谢。所以我必须初始化我的每一个常量?
  • @sarar 当然,每个变量都需要以某种方式初始化。假设你有这个const int a;,然后你有const int b = a + 10;,b的值是多少?
  • much_a_chos- undefined...明白了。
猜你喜欢
  • 1970-01-01
  • 2012-10-17
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
相关资源
最近更新 更多