【问题标题】:use of undeclared identifier for private variables within a class (C++) [closed]对类中的私有变量使用未声明的标识符(C++)[关闭]
【发布时间】:2018-10-10 21:39:40
【问题描述】:

我正在尝试对类中的私有变量使用 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() 函数中突出显示类型、名称、零件编号和价格,并出现上述错误。 如果在类中声明了变量,为什么它不能识别?

【问题讨论】:

  • 你知道你试图在两个已经是std::string的成员变量上调用std::to_string吗?
  • 好电话。感谢您指出这一点。

标签: c++ tostring


【解决方案1】:

您需要在.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);
}

【讨论】:

  • 命名空间应该是类名。所有类成员的作用域都是类名。
  • 谢谢。所以你必须对每个函数都这样做,即使你是在类本身中定义它?
  • 不,如果内联定义(即在 .h 文件中),则不需要这样做。仅在 .cpp 文件中需要
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 1970-01-01
相关资源
最近更新 更多