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

时间:2013-10-02 07:08:06

标签: c++ string function object

我知道之前可能会有人问过这个问题,但我已经四处查看了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();}

因此我混淆了为什么一个有效,另一个没有。

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

的人,我明白了

3 个答案:

答案 0 :(得分:1)

未声明static(需要static std::string get_name();)。但是,get_name()的{​​{1}}是Customer实例的特定属性,因此将其Customer设置为static没有意义,这与{{1}的所有实例的名称相同}}。声明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

答案 1 :(得分:0)

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

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

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

您需要一个对象(此处为cust1)来调用其get_name成员函数(或方法)。

花些时间阅读优秀的C ++编程书的时间。

答案 2 :(得分:0)

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

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

您的代码可以使用以下之一:

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

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