gpt4 book ai didi

c++ - Was not declared in the scope 错误

转载 作者:行者123 更新时间:2023-11-28 02:23:56 25 4
gpt4 key购买 nike

我有一个保存学生数据的类(class)。在存储之前,将首先检查 ID 是否有效。在重载运算符 >> 时,我调用了 validate_id 函数。我已经将它声明为 friend ,但是在编译时,它说 'validate_id was not declared in scope 。是因为它是静态函数吗?

#include <iostream>
#include <string>
#include <locale>
#include <utility>
#include <algorithm>
#include <stdexcept>


typedef std::pair<std::string, std::string> Name;

class Student {

public:
Student(){};

bool operator <( const Student& rhs ) const {
return ( id_ < rhs.id_ );
}

friend std::ostream& operator <<(std::ostream& os, const Student& s);
friend std::istream& operator >>(std::istream& is, Student& s);

private:
std::string id_;
Name name_;

static bool validate_id(const std::string& id){
if(id.length() != 9 && id[0] != 'a')
return false;

for(size_t i = 1, sz = id.length(); i < sz; i++){
if(!isdigit(id[i]))
return false;
}

return true;
}

};


std::ostream& operator <<(std::ostream& os, const Student& s){
return os << s.id_ << " " << s.name_.first << " " << s.name_.second;
}

std::istream& operator >>(std::istream& is, Student& s){
is >> s.id_ >> s.name_.first >> s.name_.second;

if(!validate_id(s.id_)) // error here, says validate_id is not in scope
throw std::invalid_argument( "invalid ID" );


return is;
}

最佳答案

validate_idStudent 的静态成员,所以需要使用类的作用域来命名:

if(!Student::validate_id(s.id_))
^^^^^^^^^

关于c++ - Was not declared in the scope 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31365230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com