C++ 在类(C+;+;)中为私有变量使用未声明的标识符

C++ 在类(C+;+;)中为私有变量使用未声明的标识符,c++,tostring,C++,Tostring,我试图在类内的私有变量上使用std::to_string()函数,但得到了一个“未声明的变量”错误 下面是包含函数声明的头文件: class Auto_Part { public: Auto_Part(); Auto_Part(std::string t, std::string n, int pn, double p): type(t), name(n), part_number(pn), price(p) {}; std::string get_type() cons

我试图在类内的私有变量上使用
std::to_string()
函数,但得到了一个“未声明的变量”错误

下面是包含函数声明的头文件:

class Auto_Part
{
public:
    Auto_Part();
    Auto_Part(std::string t, std::string n, int pn, double p): type(t), name(n), part_number(pn), price(p) {};
    std::string get_type() const;
    std::string get_name() const;
    int get_part_number() const;
    double get_price() const;
    void set_type(std::string);
    void set_name(std::string);
    void set_part_number(int);
    void set_price(double);
    friend std::ostream& operator<<(std::ostream&, const Auto_Part&);
    bool operator<(const Auto_Part&) const;
    std::string to_string();

private:
    std::string type;
    std::string name;
    int part_number;
    double price;
};

我的IDE在My to_string()函数中突出显示类型、名称、零件号和价格,出现上述错误如果变量是在类中声明的,为什么它不能识别它们呢?

您需要在.cpp文件的
to_string
定义中指定名称空间(这是您的
自动部分
类)。所以你的代码应该是

std::string Auto_Part::to_string(){
    return std::to_string(type) + ", " + std::to_string(name) + ", " + std::to_string(part_number) + ", " + std::to_string(price);
}

您需要在.cpp文件的
to_string
定义中指定名称空间(这是您的
自动部分
类)。所以你的代码应该是

std::string Auto_Part::to_string(){
    return std::to_string(type) + ", " + std::to_string(name) + ", " + std::to_string(part_number) + ", " + std::to_string(price);
}

命名空间应该是类名。所有类成员的作用域都是类名。谢谢。因此,即使是在类本身中定义函数,也必须对每个函数执行此操作?不,如果是在内联(即在.h文件中)中定义函数,则不需要执行此操作。仅在.cpp filenamespace中需要它,它应该是类名。所有类成员的作用域都是类名。谢谢。因此,即使是在类本身中定义函数,也必须对每个函数执行此操作?不,如果是在内联(即在.h文件中)中定义函数,则不需要执行此操作。只有在.cpp文件中才需要它。您知道您正在尝试对两个已经是
std::string
的成员变量调用
std::to_string
?很好的调用。感谢您指出这一点。您知道您正在尝试对两个已经是
std::string
的成员变量调用
std::to_string
?很好的调用。谢谢你指出这一点。