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

标签 c++ tostring

<分区>

我正在尝试对类中的私有(private)变量使用 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;
};

这是我的 .cpp 文件中有问题的函数:

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

我的 IDE 在我的 to_string() 函数中突出显示类型、名称、零件编号和价格,并出现上述错误。 为什么在类中声明的变量无法识别?

最佳答案

您需要在 .cpp 文件的 to_string 定义中指定命名空间(即您的 Auto_Part 类)。所以你的代码应该是

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

关于c++ - 在类中使用未声明的标识符作为私有(private)变量 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749161/

相关文章:

c++ - 从 plasmoid qml 调用 c++ 槽

C++ - Qt Creator 中的 Poco 库

c++ - 如何验证 rect 是否在 OpenCV 中的 cv::Mat 内?

c++ - 你如何实现语法高亮?

c# - tostring ("000.0") 生成错误值

c# - 要用属性或字段覆盖 ToString() 方法?

javascript将带前导零的数字转换为字符串它将十进制数更改为八进制数

Java - 通过 TCP 传递对象的 ArrayList

c++ - 我可以保证以负偏移访问指针吗?

java - linkedList 的 toString 方法