不能在没有对象的情况下调用成员函数 std::string class::function()

Cannot call member function std::string class::function() without object

本文关键字:string std class function 函数 成员 对象 调用 情况下 不能      更新时间:2023-10-16

我知道以前似乎有人问过这个问题,但我环顾四周,static方法对我不起作用。这是我的代码:

struct Customer {
public:
    string get_name();
private:
    string customer,first, last;
};

这是我调用函数的地方:

void creation::new_account() {
Customer::get_name(); //line it gives the error on.
}

下面是一些编译良好的代码示例。

struct Creation { public: string get_date(); private: string date; };

那我叫它的方式是一样的

void Creation::new_account() { Creation::get_date();}

因此,我很困惑为什么一个有效而另一个无效。

编辑:好的,我明白了,我刚刚意识到我正在函数定义中调用另一个结构的函数,该函数定义是不同类的一部分。我明白了,感谢所有回答的人

它没有声明static(需要static std::string get_name();)。但是,Customerget_name()Customer实例的特定属性,因此将其static没有意义,这是所有 Customer 实例的相同名称。声明一个 Customer 对象并使用它。将名称提供给 Customer 的构造函数是有意义的,因为客户肯定不能没有名称而存在:

class Customer {
public:
    Customer(std::string a_first_name,
             std::string a_last_name) : first_name_(std::move(a_first_name)),
                                        last_name_(std::move(a_last_name)) {}
    std::string get_name();
private:
    std::string first_name_;
    std::string last_name_;
};

声明 Customer 的实例:

Customer c("stack", "overflow");
std::cout << c.get_name() << "n";

由于您的get_name未声明为静态,因此它是一个成员函数。

Customer类中可能需要一些构造函数。 假设你有一些,你可以编码

 Customer cust1("foo123","John","Doe");
 string name1 = cust1.get_name();

你需要一个对象(这里cust1)来调用它的get_name成员函数(或方法)。

是时候花很多时间阅读一本好的C++编程书了。

"

static方法对我不起作用"。这不是一种方法,而是语言的工作方式。

如果你想在没有具体对象的情况下调用某个方法,你需要它是静态的。否则,您需要一个对象。

您的代码将用于以下其中一项:

struct Customer {
public:
    static string get_name();
private:
    string customer,first, last;
};

void creation::new_account() {
    Customer c;
    //stuff
    c.get_name();
}